﻿using Hsp.Auto.Common;
using Hsp.Auto.Common.Data;
using Hsp.Auto.Common.Utility;
using Hsp.Auto.DataAccess;
using Hsp.Auto.DataAccess.Data;
using Hsp.Auto.DataFactory;
using Hsp.Auto.Generator.Utility;
using Hsp.Auto.Interface;
using Hsp.Auto.Model;
using Hsp.Auto.Model.Dtos;
using Hsp.Auto.Model.Models;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Xml.Linq;

namespace Hsp.Auto.Generator
{
    public partial class FormMain : Form
    {
        /// <summary>
        /// 数据库配置服务类
        /// </summary>
        private static readonly IDbConfigService configHelper = SimpleFactory.CreateInstance<IDbConfigService>(DBType.SQLite, "DbConfigService");

        /// <summary>
        /// 数据库连接配置
        /// </summary>
        public static DbConfigs? DbConfig = null;

        /// <summary>
        /// UTF-8编码
        /// </summary>
        private UTF8Encoding utf8 = new UTF8Encoding(false);

        /// <summary>
        /// 输出程序引用文件信息
        /// </summary>
        public static ReferenceMaterials? RefMaterial = null;

        private static string? strConn = string.Empty;
        private static string? strDbName = string.Empty;
        private static string? selectTableConn = string.Empty;

        private static bool isLogicalDelete = false; //  是否逻辑删除
        private static bool isInheritsBase = false; // 是否实体继承基类
        private static bool isEntityAttribute = false; // 实体属性是否添加特性
        private static bool isEnableLogging = false; // 是否启用控制器日志
        private static bool isEnableCaching = false; // 是否启用分布式缓存
        private static bool isSingularEntity = false; // 单数形式输出实体名

        private static int bootstrapVersion = 4; // Bootstrap版本
        private static int frameworkVersion = 2; // 系统框架：1-.Net Framework；2-.Net Core(.net)

        private readonly OpenFileDialog _opendialog;
        private readonly SaveFileDialog _savedialog;
        private string? DefaultSelectedPath = string.Empty;

        private Pluralizer _pluralizer = new Pluralizer(); // 单复数服务实例

        #region 构造函数

        /// <summary>
        ///  构造函数
        /// </summary>
        [Obsolete]
        public FormMain()
        {
            LogHelper.WriteLog($"FormMain {DateTime.Now:yyyy-MM-dd HH:mm:ss} 构造函数...");

            InitializeComponent();

            #region 编码优化

            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding encoding = Encoding.GetEncoding("GB2312");

            #endregion

            #region 数据库连接参数初始化

            var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            Hsp.Auto.SQLite.DataHelper.SetConnectionString(connectionString);

            InitMain();

            #endregion

            #region 正式平台命名空间

            //this.txtModelSpaceName.Text = "Riamb.eRecycling.Model"; // 实体数据命名空间
            //this.txtBllSpaceName.Text = "Riamb.eRecycling.Service"; // 业务逻辑层命名空间
            //this.txtSpaceName.Text = "Riamb.eRecycling";
            //DefaultSelectedPath = "D:\\HYQC\\Entity";
            //this.txtSavePath.Text = DefaultSelectedPath;

            #endregion

            #region 检查全局复选框状态

            // 检查全局复选框状态
            CheckLogicalDelete(this.cbxLogicalDelete);
            CheckEntityInherits(this.cbxEntityInherits);
            CheckEntityAttribute(this.cbxEntityAttribute);
            CheckEnableLogging(this.cbxEnableLogging);
            CheckEnableCaching(this.cbxEnableCaching);
            CheckSingularEntity(this.cbxSingularEntity);

            #endregion

            #region 启用ORM特性

            CheckEfCoreAttribute(this.cbxEfCoreAttribute); // 实体属性是EfCore特性
            CheckSqlSugarAttribute(this.cbxSqlSugarAttribute); // 实体属性是SqlSugar特性
            CheckDapperAttribute(this.cbxDapperAttribute); // 实体属性是Dapper特性

            #endregion

            var dialogOpen = new OpenFileDialog
            {
                Multiselect = false,
                Filter = @"Text文件(*.txt;*.bat;*.webconfig;*.cs;*.aspx)|*.txt;*.bat;*.webconfig;*.cs;*.aspx"
            };
            _opendialog = dialogOpen;

            var dialogSave = new SaveFileDialog
            {
                Filter = @"Text文件(*.txt;*.bat;*.webconfig;*.cs;*.aspx)|*.txt;*.bat;*.webconfig;*.cs;*.aspx"
            };
            _savedialog = dialogSave;

            this.打开OToolStripMenuItem.Click += new System.EventHandler(this.打开OToolStripMenuItem_Click!);
            this.保存SToolStripMenuItem.Click += new System.EventHandler(this.保存SToolStripMenuItem_Click!);
            this.退出XToolStripMenuItem.Click += new System.EventHandler(this.退出XToolStripMenuItem_Click!);
            this.关于AToolStripMenuItem.Click += new System.EventHandler(this.关于AToolStripMenuItem_Click!);

        }

        /// <summary>
        /// 打开菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_opendialog.ShowDialog() != DialogResult.OK) return;

            //string fileName = _opendialog.FileName;
            //StreamReader reader = null;

            // 打开文件逻辑
        }

        /// <summary>
        /// 保存菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_savedialog.ShowDialog() == DialogResult.OK)
            {
                // 保存逻辑

                ReferenceMaterialSave();
            }
        }

        /// <summary>
        /// 退出菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 关于菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new FormAbout().Show();
        }

        /// <summary>
        /// 关于菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbout_Click(object sender, EventArgs e)
        {
            new FormAbout().Show();
        }

        #endregion

        #region 数据库复选框列表点击事件

        /// <summary>
        /// 数据库复选框列表点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void databaseCheckList_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            CheckedListBox control = (CheckedListBox)sender;

            #region 设置单选

            if (control.CheckedItems.Count > 0)
            {
                for (int i = 0; i < control.Items.Count; i++)
                {
                    if (i != e.Index)
                    {
                        control.SetItemChecked(i, false);
                    }
                }
            }

            #endregion

            #region MyRegion

            //strDbName = control.SelectedItem.ToString();
            //strConn += $"database={strDbName};";
            //selectTableConn = strConn;

            //using MySqlConnection connection = new MySqlConnection(selectTableConn);
            //connection.Open();

            //string selectDataBaseListSql = $"SELECT table_name AS NAME FROM information_schema.tables WHERE table_schema='{strDbName}' AND table_type='base table';";
            ////SqlCommand sqlCommand = new SqlCommand(selectDataBaseListSql, connection);
            ////SqlDataReader dataReader = sqlCommand.ExecuteReader();
            ////this.tableCheckList.Items.Clear();
            ////while (dataReader.Read())
            ////{
            ////    this.tableCheckList.Items.Add(dataReader["NAME"].ToString());
            ////}

            //DataSet dataSet = MySqlHelper.ExecuteDataset(connection, selectDataBaseListSql);

            //if (dataSet.Tables.Count > 0)
            //{
            //    foreach (DataRow dr in dataSet.Tables[0].Rows)
            //    {
            //        this.tableCheckList.Items.Add(dr["NAME"].ToString());
            //    }
            //}

            #endregion
        }

        #endregion

        #region 0）生成开发代码

        /// <summary>
        /// 0）生成开发代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateAndSaveFile_Click(object sender, EventArgs e)
        {
            #region MyRegion

            //if (string.IsNullOrWhiteSpace(txtBllSpaceName.Text))
            //{
            //    MessageBox.Show("请输入业务逻辑层命名空间！！");
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(txtDalSpaceName.Text))
            //{
            //    MessageBox.Show("请输入数据访问层命名空间！！");
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(txtModelSpaceName.Text))
            //{
            //    MessageBox.Show("请输入实体类命名空间！！");
            //    return;
            //}

            //DataAccessFactory.CreateInstance<ITableService>();
            //Dictionary<string, Dictionary<string, string>> tabledicList = new Dictionary<string, Dictionary<string, string>>();
            //Dictionary<string, List<Columns>> tabledicList = new Dictionary<string, List<Columns>>();

            // 数据库表名称，单选
            //string selectDatabaseName = this.databaseCheckList.SelectedItem.ToString();
            //if (string.IsNullOrEmpty(selectDatabaseName))
            //{
            //    MessageBox.Show("请选择数据库！！");
            //    return;
            //}

            //string selectTableConn = strConn + $"database={selectDatabaseName};";
            //string selectFileds = $"select COLUMN_NAME,DataType from information_schema.COLUMNS where TABLE_Name = '{tabelName}'";

            //foreach (string tabelName in this.tableCheckList.CheckedItems)
            //{
            //    //List<string> attrList = null;
            //    List<Columns> columnList = dbHelper.ColumnList<Columns>(tabelName, selectTableConn);

            //    //Dictionary<string, string> propTypediclist = new Dictionary<string, string>();
            //    //using (SqlConnection connection = new SqlConnection(selectTableConn))
            //    //{
            //    //    connection.Open();
            //    //    SqlCommand sqlCommand = new SqlCommand(selectFileds, connection);
            //    //    SqlDataReader dataReader = sqlCommand.ExecuteReader();
            //    //    while (dataReader.Read())
            //    //    {
            //    //        propTypediclist.Add(dataReader["COLUMN_NAME"].ToString(), dataReader["DataType"].ToString());
            //    //    }
            //    //}
            //    tabledicList.Add(tabelName, columnList);
            //}

            //var type = DBType.SqlServer;
            //var dbType = DbConfig.DBType;

            #endregion

            FormUtils.ShowProcessing("正在生成代码，请稍等......", this, arg =>
            {
                #region 根据数据库类型设置数据库连接

                // 数据库类型
                DBType dbType = (DBType)Enum.Parse(typeof(DBType), DbConfig?.DBType!);

                switch (dbType)
                {
                    case DBType.SqlServer:
                        Hsp.Auto.SqlServer.DataHelper.SetConnectionString(DbConfig?.ConnString);
                        break;
                    case DBType.MySql:
                        Hsp.Auto.MySql.DataHelper.SetConnectionString(DbConfig?.ConnString);
                        break;
                    case DBType.SQLite:
                        Hsp.Auto.SQLite.DataHelper.SetConnectionString(DbConfig?.ConnString);
                        break;
                    default:
                        throw new ArgumentException("未知数据库类型！");
                }

                #endregion

                #region 数据库表处理

                List<string> tabelList = (from string tabelName in this.tableCheckList.CheckedItems
                                          select tabelName).ToList();

                // 库表名称集合，逗号隔开
                var tableNames = string.Join(",", tabelList);

                //if (string.IsNullOrEmpty(tableNames))
                //{
                //    MessageBox.Show("请选择数据库表！！");
                //    return;
                //}

                #endregion

                #region 数据读取

                ITableService dbHelper = SimpleFactory.CreateInstance<ITableService>(dbType, "TableService");

                var dbName = dbHelper.CurrentDbName(); // 当前库名
                List<Tables> tableList = dbHelper.TableList<Tables>(strDbName, tableNames); // 表列表
                List<Views> viewList = dbHelper.ViewList<Views>(strDbName); // 视图列表

                List<Columns> columnList = new(); // 表列项
                List<Columns> viewColumnList = new(); // 视图列项
                List<KeyColumns> keyColumnListList = new();// 表主键

                if (DBType.SqlServer == dbType)
                {
                    columnList = dbHelper.ColumnList<Columns>(strDbName, tableNames);
                    viewColumnList = dbHelper.ViewColumnList<Columns>(strDbName);
                    keyColumnListList = dbHelper.KeyColumnList<KeyColumns>(strDbName, tableNames);
                }
                if (DBType.MySql == dbType)
                {
                    columnList = dbHelper.ColumnList<Columns>(strDbName, tableNames);
                    viewColumnList = dbHelper.ViewColumnList<Columns>(strDbName);
                    keyColumnListList = dbHelper.KeyColumnList<KeyColumns>(strDbName, tableNames);
                }
                if (DBType.SQLite == dbType)
                {
                    columnList = dbHelper.SqliteColumnList<Columns>(tableNames);
                    keyColumnListList = dbHelper.KeyColumnList<KeyColumns>(strDbName, tableNames);
                }

                // 表引用
                List<DbReferences> referenceList = new();
                if (DBType.SqlServer == dbType)
                {
                    referenceList = dbHelper.ReferenceList<DbReferences>(tableNames);
                }
                if (DBType.MySql == dbType)
                {
                    referenceList = dbHelper.ReferenceList<DbReferences>(strDbName, tableNames);
                }

                // 表索引
                List<DbIndexs> indexList = new();
                if (DBType.SqlServer == dbType)
                {
                    indexList = dbHelper.IndexList<DbIndexs>(tableNames);
                }
                if (DBType.MySql == dbType)
                {
                    indexList = dbHelper.IndexList<DbIndexs>(strDbName, tableNames);
                }

                // 枚举数据
                List<Enumerate> enumList = new();
                if (DBType.MySql == dbType)
                {
                    enumList = dbHelper.EnumList<Enumerate>(strDbName);
                }

                #endregion

                #region 选择目录

                var selectPath = DefaultSelectedPath;
                if (string.IsNullOrEmpty(selectPath))
                {
                    selectPath = this.txtSavePath.Text.Trim();

                }
                if (string.IsNullOrEmpty(selectPath))
                {
                    FolderBrowserDialog path = new();
                    path.ShowDialog();
                    selectPath = path.SelectedPath;
                    DefaultSelectedPath = selectPath;
                    this.txtSavePath.Text = selectPath;
                    // 保存目录
                    configHelper.SaveDefaultPath(RefMaterial!.Id, selectPath);
                }

                #endregion

                #region 开始工作

                //开始生成实体代码文件
                CreateModelFile(selectPath, tableList, columnList, keyColumnListList, referenceList);

                // 视图实体
                CreateViewModelFile(selectPath, viewList, viewColumnList);

                // 生成区域控制器视图代码文件
                CreateControllerFile(dbName, selectPath, tableList, columnList);

                // 开始创建生成表示层代码Html文件
                CreateHtmlFile(selectPath, tableList, columnList); // TableList
                CreateTreeListFile(selectPath, tableList, columnList); // TreeList

                // 资源文件处理
                CreateViewResourcesFile(selectPath, tableList, columnList);

                // 生成业务逻辑层代码文件
                //CreateBllFile(selectPath, tableList, columnList);
                CreateServiceFile(selectPath, tableList, columnList);

                // 生成数据访问层代码文件
                //CreateDalFile(selectPath, tableList, columnList);
                CreateRepositoryFile(selectPath, tableList, columnList);

                // 其他输出
                CreateOtherFile(dbName, selectPath, tableList, columnList, referenceList, indexList);
                CreateEnumFile(selectPath, enumList);

                #endregion

                MessageBox.Show($"代码已经生成在【{selectPath}】下！");
            });
        }

        #endregion

        #region 基本方法

        #region 表实体名称

        // 转换规则：实体是单数形式，集合或者列表(上下文中)是复数形式；
        // 如：  public virtual DbSet<AuthUser> AuthUsers { get; set; }
        //      _context.AuthUsers.Skip(0).Take(50).ToListAsync()
        //      public partial class AuthUser
        // 转移到 MainExt 扩展类中

        /*
        /// <summary>
        /// 处理Asp.Net Core EF6 实体转换后的表实体名称(单数)
        /// 规则：去掉“_”分隔符，并每个分隔区域的首字符大写，其余不变
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="isPluralize">是否复数形式：0-否；1-是；</param>
        /// <returns></returns>
        private string GetSingularModelName(string tableName)
        {
            return GetModelName(tableName, false);
        }

        /// <summary>
        /// 处理Asp.Net Core EF6 实体转换后的表实体名称(复数)
        /// 规则：去掉“_”分隔符，并每个分隔区域的首字符大写，其余不变
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="isPluralize">是否复数形式：0-否；1-是；</param>
        /// <returns></returns>
        private string GetPluralizeModelName(string tableName, bool isPluralize = false)
        {
            return GetModelName(tableName, true);
        }

        /// <summary>
        /// 处理Asp.Net Core EF6 实体转换后的表实体名称
        /// 规则：去掉“_”分隔符，并每个分隔区域的首字符大写，其余不变
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="isPluralize">是否复数形式：null-不转换；0-否；1-是；</param>
        /// <returns></returns>
        private string GetModelName(string tableName, bool? isPluralize = null)
        {
            if (tableName == null) return "Null";
            var name = tableName.Trim();
            if (name.IndexOf('_') > -1)
            {
                name = string.Empty;
                var arr = tableName.Split('_');
                foreach (string s in arr)
                {
                    name += s.ToUpperFirst();
                }
            }
            else
            {
                name = name.ToUpperFirst();
            }
            return isPluralize == null ? name : (bool)isPluralize ? Pluralize(name) : Singularize(name);
        }
        */

        #endregion

        /*
        /// <summary>
        /// 处理Asp.Net Core EF6 实体转换后的表Dto名称
        /// 规则：去掉“_”分隔符，并每个分隔区域的首字符大写，其余不变
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        private string GetDtoName(string tableName)
        {
            var name = tableName.ToSingularModelName();
            //var singular = this.Singularize(name);
            return name + "Dto";
        }

        private string GetViewModelName(string tableName)
        {
            var name = tableName.ToSingularModelName();
            //var singular = this.Singularize(name);
            return name + "ViewModel";
        }
        */

        /// <summary>
        /// 获取表代称（首字母，小写）
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        private static string GetAlternativeName(string tableName)
        {
            try
            {
                var arr = tableName.ToLower().Split('_');
                return (arr.Length == 1 ? arr[0] : arr[arr.Length - 1]).FirstOrDefault().ToString();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"获取表代称（首字母，小写）", ex);
                throw;
            }
        }

        /// <summary>
        /// 根据表名称获取类名称
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        private string GetClassName(string tableName)
        {
            var name = tableName.Trim();
            if (name.IndexOf('_') > -1)
            {
                name = string.Empty;
                var arr = tableName.Split('_');
                foreach (string s in arr)
                {
                    name += s.ToUpperFirst();
                }
            }
            else
            {
                name = name.ToUpperFirst();
            }
            return this.Singularize(name);
        }

        /// <summary>
        /// 获取实体实例化名称
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        private string GetInstanceModelName(string tableName)
        {
            var name = tableName.ToLower();
            if (name.IndexOf('_') > -1)
            {
                name = string.Empty;
                var arr = tableName.Split('_');
                for (int i = 0; i < arr.Length; i++)
                {
                    var s = arr[i];
                    if (i == 0)
                    {
                        name += s;
                    }
                    else
                    {
                        name += s.ToUpperFirst();
                    }
                }
            }
            else
            {
                name = name.ToUpperFirst();
            }

            return this.Singularize(name);
        }

        /// <summary>
        /// 获取实体中外键定义实例化名称
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        private string GetInstanceName(string tableName)
        {
            var name = tableName.Trim();
            if (tableName.ToLower().EndsWith("bill"))
            {
                name = "bill";
            }
            else if (tableName.IndexOf("order", StringComparison.CurrentCultureIgnoreCase) > -1)
            {
                name = "order";
            }
            else if (tableName.IndexOf('_') > -1)
            {
                var arr = name.Split('_');
                name = arr[^1].Trim(); // arr[arr.Length - 1].Trim();
            }

            // 单数形式
            var singular = this.Singularize(name);

            return singular.ToUpperFirst();
        }

        /// <summary>
        /// 获取控制器名称(复数形式)
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        private string GetControllerName(string tableName)
        {
            var name = tableName;
            if (name.IndexOf('_') > -1)
            {
                name = string.Empty;
                var arr = tableName.Split('_');
                foreach (string s in arr)
                {
                    name += s.ToUpperFirst();
                }
            }
            else
            {
                name = name.ToUpperFirst();
            }

            return _pluralizer.Pluralize(name);
            //return System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(new CultureInfo("en")).Pluralize(name);
        }

        /// <summary>
        /// 获取表字段修正后的名称
        /// </summary>
        /// <param name="columnName">字段名称</param>
        /// <returns></returns>
        private static string GetColumnName(string? columnName)
        {
            if (string.IsNullOrEmpty(columnName)) return string.Empty;
            var name = columnName;
            if (name.IndexOf('_') > -1)
            {
                name = string.Empty;
                var arr = columnName.Split('_');
                foreach (string s in arr)
                {
                    name += s.ToUpperFirst();
                }
            }
            else
            {
                name = name.ToUpperFirst();
            }
            return name;
        }

        /// <summary>
        /// 获取实例化列名称
        /// </summary>
        /// <param name="columnName">字段名称</param>
        /// <returns></returns>
        private string GetInstanceColumn(string columnName)
        {
            if (string.IsNullOrEmpty(columnName)) return "";

            var name = columnName.ToLower();
            if (name.EndsWith("id"))
            {
                name = name[0..^2];
            }
            else
            {
                name = "_" + name;
            }
            // 单数形式
            var singular = this.Singularize(name);

            return singular.ToUpperFirst();
        }

        /// <summary>
        /// 返回单词的单数形式
        /// </summary>
        /// <param name="word">单词</param>
        /// <returns></returns>
        private string Singularize(string word)
        {
            return _pluralizer.Singularize(word);
            //return System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(new CultureInfo("en")).Singularize(word); //.Pluralize
        }

        /// <summary>
        /// 返回单词的复数形式
        /// </summary>
        /// <param name="word">单词</param>
        /// <returns></returns>
        private string Pluralize(string word)
        {
            return _pluralizer.Pluralize(word);
            //return System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(new CultureInfo("en")).Singularize(word); //.Pluralize
        }

        ///// <summary>
        ///// 字符串改为首字符大写，其余小写
        ///// </summary>
        ///// <param name="str">字符串</param>
        ///// <returns></returns>
        //private static string ToUpperFirst(string str)
        //{
        //    if (string.IsNullOrEmpty(str)) return "";

        //    if (str.ToLower() == "qq") str = "Qq";
        //    if (str.ToLower() == "id") str = "Id";
        //    if (str.ToLower() == "pid") str = "Pid";
        //    if (str.Contains("QQ")) str = str.Replace("QQ", "Qq");
        //    if (str.Contains("ID")) str = str.Replace("ID", "Id");
        //    if (str.Contains("API")) str = str.Replace("API", "Api");

        //    //str = str.ToLower();
        //    char[] a = str.ToCharArray();
        //    a[0] = char.ToUpper(a[0]);
        //    return new string(a);
        //}

        ///// <summary>
        ///// 字符串改为首字符小写
        ///// </summary>
        ///// <param name="str">字符串</param>
        ///// <returns></returns>
        //private static string ToLowerFirst(string str)
        //{
        //    if (string.IsNullOrEmpty(str)) return "";
        //    char[] a = str.ToCharArray();
        //    a[0] = char.ToLower(a[0]);
        //    return new string(a);
        //}

        #endregion

        #region 1）生成实体代码CS文件

        /// <summary>
        /// 是否可继承实体基类
        /// </summary>
        /// <param name="columnList">表列数据</param>
        /// <returns></returns>
        private static bool CanInheritsBase(List<Columns> columnList)
        {
            var hasCreatorId = false;
            var hasModifierId = false;
            var hasCreateTime = false;
            var hasModifiedTime = false;

            foreach (var column in columnList)
            {
                if (column.Name == "CreatorId") hasCreatorId = true;
                if (column.Name == "CreateTime" && column.DataType!.ToLower() != "timestamp") hasCreateTime = true;
                if (column.Name == "ModifierId") hasModifierId = true;
                if (column.Name == "ModifiedTime" && column.DataType!.ToLower() != "timestamp") hasModifiedTime = true;
            }

            return isInheritsBase && hasCreatorId && hasModifierId && hasCreateTime && hasModifiedTime;
        }

        /// <summary>
        /// 是否继承基类字段
        /// </summary>
        /// <param name="fieldName">字段名称</param>
        /// <returns></returns>
        private static bool IsInheritsField(string fieldName)
        {
            if (fieldName == "CreatorId") return isInheritsBase;
            if (fieldName == "CreateTime") return isInheritsBase;
            if (fieldName == "ModifierId") return isInheritsBase;
            if (fieldName == "ModifiedTime") return isInheritsBase;
            return false;
        }

        private string tabOne = "    "; // 跳一格
        private string tabTwo = "        "; // 跳两格
        private string tabTre = "            "; // 跳三格

        /// <summary>
        /// 开始创建实体CS文件
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        /// <param name="keyColumns">表主键列表</param>
        /// <param name="referenceList">表引用列表</param>

        private void CreateModelFile(string selectPath, List<Tables> tableList, List<Columns> columnList, List<KeyColumns> keyColumns, List<DbReferences> referenceList)
        {
            try
            {
                string modelPath = $"{selectPath}\\Model\\Models\\";
                string dtoPath = $"{selectPath}\\Model\\Dtos\\";
                string viewPath = $"{selectPath}\\Model\\Views\\"; // 视图数据对象

                FileHelper.FilePathCheck(modelPath);
                FileHelper.FilePathCheck(dtoPath);
                //FileHelper.FilePathCheck(viewPath);

                var spaceName = txtSpaceName.Text.Trim();
                var modelSpaceName = spaceName + ".Model";
                StringBuilder sb = new();

                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 表名

                    if (table.Comment == null) continue;

                    var tableDesc = table.Comment.Replace(":", "："); // 表描述
                    //var tableViewName = tableName.ToSingularModelName(); // 表实体名称
                    //if (isSingularEntity) tableViewName = tableViewName;
                    var tableModelName = tableName.ToSingularModelName(); // 表实体名称

                    var tableDtoName = tableModelName + "Dto"; // 表Dto对象
                    var tableViewModelName = tableModelName + "ViewModel"; // 表ViewModel对象
                    var baseTableDesc = string.IsNullOrEmpty(tableDesc) ? tableName : tableDesc.Split('：')[0]; // 表基本描述【描述中冒号前面的部分】
                    baseTableDesc = baseTableDesc.TrimEnd('表');

                    var modelFilePath = $"{modelPath}{tableModelName}.cs";
                    var dtoFilePath = $"{dtoPath}{tableDtoName}.cs";
                    var viewModelFilePath = $"{viewPath}{tableViewModelName}.cs";

                    if (string.IsNullOrEmpty(baseTableDesc))
                    {
                        baseTableDesc = $"{{{baseTableDesc}}}"; // 如果表没有添加中文注释，以此此方法方便替换
                    }

                    // 表列项数据
                    var tableColumn = columnList.Where(entity => entity.TableName == tableName).ToList();
                    var isTree = IsTree(tableColumn); // 是否树结构表
                    var hasDisabled = HasDisabled(tableColumn); // 是否有Disabled列

                    // 被引用数据
                    var referenceTable = referenceList?.Where(entity => entity.TableName == tableName).ToList();

                    // 外键列数据
                    var keyColumnTable = keyColumns?.Where(entity => entity.TableName == tableName).ToList();

                    #region Model 实体数据对象

                    sb = new StringBuilder();

                    #region 引用文件

                    // 实体对象引用文件
                    var referenceMaterials = txtModelReferenceMaterials.Text;

                    if (string.IsNullOrEmpty(referenceMaterials))
                    {
                        // 允许输出SqlSugar实体特性
                        if (isSqlSugarAttribute)
                        {
                            sb.AppendLine($"using SqlSugar;");
                        }
                        sb.AppendLine($"using System;");
                        sb.AppendLine($"using System.Collections.Generic;");
                        sb.AppendLine($"using System.ComponentModel;");
                        sb.AppendLine($"using System.ComponentModel.DataAnnotations;");
                        sb.AppendLine($"using System.ComponentModel.DataAnnotations.Schema;");
                        sb.AppendLine($"using System.Text;");
                    }
                    else
                    {
                        if (!referenceMaterials.Contains("SqlSugar"))
                        {
                            sb.AppendLine($"using SqlSugar;");
                        }
                        sb.AppendLine($"{referenceMaterials}");
                    }
                    sb.AppendLine();

                    #endregion

                    #region 命名空间

                    sb.AppendLine($"namespace {modelSpaceName}.Models");

                    #endregion

                    sb.AppendLine("{");

                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {baseTableDesc}数据实体");
                    sb.AppendLine($"{tabOne}/// </summary>");

                    // 允许输出实体特性
                    if (isEntityAttribute)
                    {
                        sb.AppendLine($"{tabOne}[Table(\"{tableName}\")]");
                    }
                    // 允许输出SqlSugar实体特性
                    if (isSqlSugarAttribute)
                    {
                        sb.AppendLine($"{tabOne}[SugarTable(\"{tableName}\")]");
                    }

                    // 判断是否继承实体基类
                    var canInheritsBase = CanInheritsBase(tableColumn);
                    sb.AppendLine($"{tabOne}public partial class {tableModelName}{(canInheritsBase ? " : BaseModel" : "")}");

                    sb.AppendLine($"{tabOne}{{");

                    #region 构造函数

                    if (referenceTable?.Count > 0)
                    {
                        sb.AppendLine($"{tabTwo}public {tableModelName}()");
                        sb.AppendLine($"{tabTwo}{{");

                        // 被引用的数据
                        foreach (var reference in referenceTable)
                        {
                            var referencedTableName = reference.PrimarykeyTableName.ToSingularModelName();
                            if (referencedTableName == "Null") continue;
                            sb.AppendLine($"{tabTre}{referencedTableName} = new HashSet<{referencedTableName}>();");
                        }

                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine(" ");
                    }

                    #endregion

                    #region 实体属性

                    foreach (var column in tableColumn)
                    {
                        if (column == null)
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(column.Name))
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(column.DataType))
                        {
                            continue;
                        }

                        if (column.DataType.ToLower() == "timestamp")
                        {
                            continue;
                        }

                        var columnName = column.Name; // 列名
                        var columnDesc = column.Comment?.Replace(":", "："); // 列描述【列基本描述：枚举描述】
                        columnDesc = columnDesc?.Replace("\n", ""); // 处理换行符
                        if (string.IsNullOrEmpty(columnDesc)) columnDesc = columnName;
                        var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                        if (canInheritsBase && IsInheritsField(column?.Name ?? ""))
                        {
                            continue; // 如果允许实体继承基类，则输出非继承字段，否则输出全部字段
                        }

                        string? strType = GetTypeMethod(column.DataType);
                        if (column.DataType.ToLower() == "date")
                        {
                            strType = frameworkVersion == 2 ? "DateOnly" : "DateTime"; // 日期 Date
                        }
                        else if (column.DataType.ToLower() == "time")
                        {
                            strType = frameworkVersion == 2 ? "TimeOnly" : "DateTime"; // 时间 Time
                        }

                        sb.AppendLine($"{tabTwo}/// <summary>");
                        sb.AppendLine($"{tabTwo}/// {columnDesc}");
                        sb.AppendLine($"{tabTwo}/// </summary>");

                        #region 必填项提示特性

                        if (column.IsPK == 0 && column.Nullable == 0 && column.DataType!.ToLower() != "int")
                        {
                            sb.AppendLine($"{tabTwo}[Required(ErrorMessage=\"{{{0}}}不能为空\")]");
                        }

                        #endregion

                        #region 显示特性

                        var sugarColumnPK = string.Empty;

                        if (column.IsPK == 0)
                        {
                            // 非主键输出显示特性
                            sb.AppendLine($"{tabTwo}[DisplayName(\"{baseColumnDesc?.Replace("\\", "-").TrimEnd('-')}\")]");
                        }
                        else
                        {
                            sb.AppendLine($"{tabTwo}[Key]");
                            if (isSqlSugarAttribute && !string.IsNullOrEmpty(strType))
                            {
                                if (strType.Contains("int", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    sugarColumnPK = "INT";
                                    //sb.AppendLine($"{tabTwo}[SugarColumn(IsPrimaryKey=true,IsIdentity=true)]");
                                }
                                if (strType.Contains("string", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    sugarColumnPK = "STRING";
                                    //sb.AppendLine($"{tabTwo}[SugarColumn(IsPrimaryKey=true)]");
                                }
                            }
                        }

                        #endregion

                        #region 长度提示特性

                        if (column.Nullable == 1 && column.DataType!.ToLower().Contains("char") && column.Length < 50)
                        {
                            sb.AppendLine($"{tabTwo}[StringLength({column.Length})]");
                        }

                        #endregion

                        #region 数据类型验证特性

                        var dataType = "";

                        if (columnName.ToLower().Contains("email"))
                        {
                            // .IndexOf("email", StringComparison.CurrentCultureIgnoreCase) > -1
                            dataType = "EmailAddress"; // Email数据类型验证
                        }
                        else if (columnName.ToLower().IndexOf("phone") > -1
                              || columnName.ToLower().IndexOf("mobile") > -1)
                        {
                            dataType = "PhoneNumber"; // 手机号码数据类型验证
                        }
                        else if ((baseColumnDesc?.IndexOf("金额") > -1
                               || baseColumnDesc?.IndexOf("价") > -1
                               || baseColumnDesc?.IndexOf("费") > -1) && column.DataType == "decimal")
                        {
                            dataType = "Currency"; // 金额类型数据类型验证
                        }
                        else if ((baseColumnDesc?.IndexOf("密码") > -1
                            || columnName.ToLower().IndexOf("password") > -1) && column.DataType == "varchar")
                        {
                            dataType = "Password"; // 密码
                        }
                        else if (column.DataType!.ToLower() == "date")
                        {
                            dataType = "Date"; // 日期 Date
                        }
                        else if (column.DataType!.ToLower() == "time")
                        {
                            dataType = "Time"; // 时间 Time
                        }
                        else if (column.DataType!.ToLower() == "datetime")
                        {
                            dataType = "DateTime"; // 日期时间
                        }
                        else if (column.DataType!.ToLower() == "dateonly")
                        {
                            dataType = "Date"; // 日期时间
                        }

                        if (!string.IsNullOrEmpty(dataType))
                        {
                            sb.AppendLine($"{tabTwo}[DataType(DataType.{dataType})]");
                        }

                        if (dataType == "Currency")
                        {
                            var strIntegralPart = "".PadLeft(column?.Length ?? 6, '9'); // 整数部分长度
                            var strFractionalPart = "".PadLeft(column.Scale ?? 2, '9'); // 小数部分长度

                            sb.AppendLine($"{tabTwo}[Range(typeof(decimal), \"0.00\", \"{strIntegralPart}.{strFractionalPart}\", ErrorMessage = \"{{0}}须在{{1}}和{{2}}之间\")]");
                        }

                        #endregion

                        #region Column特性

                        //if (columnName == "QQ")
                        //{
                        //    var dd = GetColumnName(columnName);
                        //    var bbbb = dd;
                        //}

                        var customColumnName = GetColumnName(columnName);
                        if (columnName != customColumnName)
                        {
                            sb.AppendLine($"{tabTwo}[Column(\"{columnName}\")]");
                            if (isSqlSugarAttribute)
                            {
                                if (sugarColumnPK == "INT")
                                {
                                    sb.AppendLine($"{tabTwo}[SugarColumn(IsPrimaryKey=true,IsIdentity=true, ColumnName=\"{columnName}\")]");
                                }
                                else if (sugarColumnPK == "STRING")
                                {
                                    sb.AppendLine($"{tabTwo}[SugarColumn(IsPrimaryKey=true, ColumnName=\"{columnName}\")]");
                                }
                                else
                                {
                                    sb.AppendLine($"{tabTwo}[SugarColumn(ColumnName=\"{columnName}\")]");
                                }
                            }
                            columnName = customColumnName;
                        }
                        else
                        {
                            if (sugarColumnPK == "INT")
                            {
                                sb.AppendLine($"{tabTwo}[SugarColumn(IsPrimaryKey=true,IsIdentity=true)]");
                            }
                            else if (sugarColumnPK == "STRING")
                            {
                                sb.AppendLine($"{tabTwo}[SugarColumn(IsPrimaryKey=true)]");
                            }
                            else
                            {

                            }
                        }

                        #endregion

                        #region 输出属性

                        //  && strType != "string"
                        if (frameworkVersion == 2)
                        {
                            if (column?.IsPK == 0 && column.Nullable == 1) strType += "?";
                            if (strType == "string" && column.Nullable == 0) strType += "?";
                        }

                        sb.AppendLine($"{tabTwo}public {strType} {columnName} {{ get; set; }}");

                        #endregion

                        sb.AppendLine();
                    }

                    #endregion

                    #region 外键数据

                    if (keyColumnTable != null)
                    {
                        foreach (var keyColumn in keyColumnTable)
                        {
                            var referencedTableName = keyColumn.ReferencedTableName.ToSingularModelName();
                            var singularName = GetInstanceColumn(keyColumn.ColumnName);
                            if (string.IsNullOrEmpty(singularName))
                            {
                                singularName = this.Singularize(keyColumn.ReferencedTableName);
                            }
                            // 允许输出SqlSugar特性
                            if (isSqlSugarAttribute)
                            {
                                sb.AppendLine($"{tabTwo}[SugarColumn(IsIgnore = true)]");
                            }
                            sb.AppendLine($"{tabTwo}public virtual {referencedTableName}? {singularName} {{ get; set; }}");
                        }
                    }
                    else
                    {
                        foreach (var column in tableColumn)
                        {
                            if (!string.IsNullOrEmpty(column.Referenced_Table_Name))
                            {
                                var referencedTableName = column.Referenced_Table_Name.ToSingularModelName();
                                var singularName = GetInstanceName(column.Name);
                                // 允许输出SqlSugar特性
                                if (isSqlSugarAttribute)
                                {
                                    sb.AppendLine($"{tabTwo}[SugarColumn(IsIgnore = true)]");
                                }
                                sb.AppendLine($"{tabTwo}public virtual {referencedTableName}? {singularName} {{ get; set; }}");
                            }
                        }
                    }

                    sb.AppendLine(" ");

                    #endregion

                    #region 被引用的数据

                    if (referenceTable != null)
                    {
                        foreach (var reference in referenceTable)
                        {
                            var referencedTableName = reference.PrimarykeyTableName.ToSingularModelName();

                            if (referencedTableName == "Null") continue;

                            // 允许输出SqlSugar特性
                            if (isSqlSugarAttribute)
                            {
                                sb.AppendLine($"{tabTwo}[SugarColumn(IsIgnore = true)]");
                            }
                            sb.AppendLine($"{tabTwo}public virtual ICollection<{referencedTableName}>? {referencedTableName} {{ get; set; }}");
                        }
                    }

                    #endregion

                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine("}");

                    File.WriteAllText(modelFilePath, sb.ToString());

                    #endregion

                    #region Dtos 数据传输对象

                    sb = new StringBuilder();

                    #region 引用文件

                    referenceMaterials = txtModelReferenceMaterials.Text;

                    if (string.IsNullOrEmpty(referenceMaterials))
                    {
                        sb.AppendLine($"using System;");
                        sb.AppendLine($"using System.Collections.Generic;");
                        sb.AppendLine($"using System.ComponentModel;");
                        sb.AppendLine($"using System.Linq;");
                        sb.AppendLine($"using System.Text;");
                    }
                    else
                    {
                        sb.AppendLine($"{referenceMaterials}");
                    }

                    sb.AppendLine($"using System.Reflection;");
                    sb.AppendLine($"using {modelSpaceName}.Models;");
                    sb.AppendLine($"using {spaceName}.Common.Constants;");
                    sb.AppendLine();

                    #endregion

                    #region 命名空间

                    sb.AppendLine($"namespace {modelSpaceName}.Dtos");

                    #endregion

                    sb.AppendLine("{");
                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {baseTableDesc}数据传输对象");
                    sb.AppendLine($"{tabOne}/// </summary>");
                    sb.AppendLine($"{tabOne}public class {tableDtoName} : {tableModelName}");
                    sb.AppendLine($"{tabOne}{{");

                    //sb.AppendLine($"        /// <summary>");
                    //sb.AppendLine($"        /// 行记录号");
                    //sb.AppendLine($"        /// </summary>");
                    //sb.AppendLine($"        public int RowNumber {{ get; set; }}");
                    //sb.AppendLine($"");
                    //sb.AppendLine($"        /// <summary>");
                    //sb.AppendLine($"        /// 记录总数");
                    //sb.AppendLine($"        /// </summary>");
                    //sb.AppendLine($"        public int RecordCount {{ get; set; }}");
                    //sb.AppendLine($"");

                    if (isTree)
                    {
                        sb.AppendLine($"        /// <summary>");
                        sb.AppendLine($"        /// 子项数量");
                        sb.AppendLine($"        /// </summary>");
                        sb.AppendLine($"        public int ChildCount {{ get; set; }}");
                        sb.AppendLine($"");
                    }

                    if (hasDisabled)
                    {
                        sb.AppendLine($"        /// <summary>");
                        sb.AppendLine($"        /// 是否禁用：0-否；1-是");
                        sb.AppendLine($"        /// </summary>");
                        sb.AppendLine($"        public string? DisabledName");
                        sb.AppendLine($"        {{");
                        sb.AppendLine($"            get");
                        sb.AppendLine($"            {{");
                        sb.AppendLine($"                return Disabled.HasValue ? EnumsHelper.GetName((EnumDisabled)Disabled) : \"\";");
                        sb.AppendLine($"            }}");
                        sb.AppendLine($"        }}");
                        sb.AppendLine($"");
                    }

                    foreach (var column in tableColumn)
                    {
                        var isOperator = false;
                        if (column.Name!.ToLower().Contains("creatorid") || column.Name.ToLower().Contains("modifierid"))
                        {
                            isOperator = true;
                            var abc = column.Name;
                        }

                        //var isTimestamp = false;
                        //if (column.DataType!.ToLower() == "timestamp")
                        //{
                        //    isTimestamp = true;
                        //}

                        if (column.IsPK == 1 && column.IsIdentity == 1) continue;
                        if (column.Name.ToLower() == "id") continue;
                        if (column.Name.ToLower() == "disabled") continue;

                        var columnName = column.Name; // 列名
                        var columnDesc = column.Comment?.Replace(":", "："); // 列描述【列基本描述：枚举描述】
                        columnDesc = columnDesc.Replace("\n", ""); // 处理换行符
                        var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】
                        if (isOperator)
                        {
                            columnDesc = columnDesc.Replace("ID", "姓名");
                        }
                        else
                        {
                            columnDesc = columnDesc.Replace("ID", "名称").Replace("编号", "名称");
                        }

                        columnDesc = columnDesc.Replace(";", "；").Replace("、", "；").Replace("（", "(").Replace("，", ",");

                        var isEnumColumn = IsEnumColumn(columnDesc);

                        if (columnDesc.IndexOf("：") > -1 && column.DataType?.IndexOf("int") > -1)
                        {
                            sb.AppendLine($"{tabTwo}/// <summary>");
                            sb.AppendLine($"{tabTwo}/// {columnDesc}");
                            sb.AppendLine($"{tabTwo}/// </summary>");

                            if (columnName.EndsWith("Id")) columnName = columnName[0..^2]; // .Substring(0, columnName.Length - 2)
                            sb.AppendLine($"{tabTwo}public string? {columnName + "Name"} {{ get; set; }}");
                            sb.AppendLine(" ");
                        }
                        else if (!string.IsNullOrEmpty(column.Referenced_Table_Name))
                        {
                            sb.AppendLine($"{tabTwo}/// <summary>");
                            sb.AppendLine($"{tabTwo}/// {columnDesc}");
                            sb.AppendLine($"{tabTwo}/// </summary>");

                            if (columnName.EndsWith("Id")) columnName = columnName[0..^2]; // 范围运算符
                            sb.AppendLine($"{tabTwo}public string? {columnName + "Name"} {{ get; set; }}");
                            sb.AppendLine(" ");
                        }
                        else if (DbConfig?.DBType == "SqlServer" && column.DataType == "uniqueidentifier"
                           || DbConfig?.DBType == "MySql" && column.DataType == "char" && column.Length == 36
                           )
                        {
                            sb.AppendLine($"{tabTwo}/// <summary>");
                            sb.AppendLine($"{tabTwo}/// {columnDesc}");
                            sb.AppendLine($"{tabTwo}/// </summary>");

                            if (columnName.EndsWith("Id")) columnName = columnName[0..^2]; // 范围运算符
                            sb.AppendLine($"{tabTwo}public string? {columnName + "Name"} {{ get; set; }}");
                            sb.AppendLine(" ");
                        }

                        if (isOperator)
                        {
                            sb.AppendLine($"{tabTwo}/// <summary>");
                            sb.AppendLine($"{tabTwo}/// {columnDesc}");
                            sb.AppendLine($"{tabTwo}/// </summary>");

                            if (columnName.ToLower().EndsWith("id")) columnName = columnName[0..^2]; // 范围运算符
                            sb.AppendLine($"{tabTwo}public string? {columnName + "Name"} {{ get; set; }}");
                            sb.AppendLine(" ");
                        }

                        if (column.DataType!.ToLower() == "timestamp")
                        {
                            sb.AppendLine($"{tabTwo}/// <summary>");
                            sb.AppendLine($"{tabTwo}/// {columnDesc}");
                            sb.AppendLine($"{tabTwo}/// </summary>");

                            sb.AppendLine($"{tabTwo}public DateTime? {columnName} {{ get; set; }}");
                            sb.AppendLine(" ");
                        }

                        if (column.Name.ToLower() == "pid")
                        {
                            sb.AppendLine($"{tabTwo}        /// <summary>");
                            sb.AppendLine($"{tabTwo}        /// 父级名称");
                            sb.AppendLine($"{tabTwo}        /// </summary>");
                            sb.AppendLine($"{tabTwo}        [DisplayName(\"父级名称\")]");
                            sb.AppendLine($"{tabTwo}        public string? PName {{ get; set; }}");
                            sb.AppendLine($"{tabTwo}");
                        }
                    }

                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine("}");

                    File.WriteAllText(dtoFilePath, sb.ToString());

                    #endregion

                    #region Views 视图数据对象

                    sb = new StringBuilder();

                    #region 引用文件

                    sb.AppendLine($"using {modelSpaceName}.Dtos;");
                    sb.AppendLine($"using Microsoft.AspNetCore.Mvc.Rendering;");
                    sb.AppendLine($"using System;");
                    sb.AppendLine($"using System.Collections.Generic;");
                    sb.AppendLine($"using System.ComponentModel.DataAnnotations;");
                    sb.AppendLine($"using System.Linq;");
                    sb.AppendLine($"using System.Reflection;");
                    sb.AppendLine($"using System.Text;");
                    sb.AppendLine($"using System.Threading.Tasks;");
                    sb.AppendLine();

                    #endregion

                    #region 命名空间

                    sb.AppendLine($"namespace {spaceName}.Web.Models");

                    #endregion

                    sb.AppendLine("{");
                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {baseTableDesc}视图实体对象");
                    sb.AppendLine($"{tabOne}/// </summary>");
                    sb.AppendLine($"{tabOne}public class {tableViewModelName} : {tableDtoName}");
                    sb.AppendLine($"{tabOne}{{");
                    sb.AppendLine();
                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine("}");

                    //File.WriteAllText(viewFilePath, sb.ToString());

                    #endregion
                }

                #region 主键处理，废弃代码

                //if (column.IsPK == 1)
                //{
                //    isInheritField = true; // 继承基类字段
                //    if (column.ColumnType == "int")
                //    {
                //        attrList.Add("PrimaryKey = true"); // 主键
                //        attrList.Add("Identity = true"); // 标识/自增
                //        attrList.Add("Insert = false"); // 非插入字段
                //    }
                //    if (column.ColumnType == "string")
                //    {
                //        attrList.Add("PrimaryKey = true"); // 主键
                //    }
                //    if (column.ColumnType == "Guid")
                //    {
                //        attrList.Add("PrimaryKey = true"); // 主键
                //    }
                //}

                //var fieldProperty = "";
                //var requiredAttribute = "";
                //var isInheritField = false;

                //if (column.Queryable == 1) // 可查询字段
                //{ }
                //var fieldAttribute = "";
                ////fieldProperty = "[Column()]";
                //List<string> attrList = new List<string>();

                //if (column.Length > 0)
                //{
                //    // 字符型字段长度
                //    attrList.Add($"Length = {column.Length}");
                //}

                //if (column.Length > 0 && column.DataType!.ToLower().Contains("int") && (column.ColumnType == "double"
                //    || column.ColumnType == "decimal"
                //    || column.ColumnType == "Single"))
                //{
                //    // 数值型字段精度和小数位
                //    attrList.Add($"Precision = {column.Numeric_Precision}");
                //    attrList.Add($"Scale = {column.NUMERIC_SCALE}");
                //}

                //// CreateTime, CreatorId, LastModifyTime, LastModifierId

                //if (column.Name.IndexOf("CreatorId") > -1
                //    || column.Name.IndexOf("CreateTime") > -1)
                //{
                //    isInheritField = true; // 继承基类字段
                //    attrList.Add("Update = false"); // 非更新字段
                //}

                //if (column.Name.IndexOf("LastModifierId") > -1
                //    || column.Name.IndexOf("LastModifyTime") > -1
                //    || column.Name.IndexOf("ModifierId") > -1
                //    || column.Name.IndexOf("ModifiedTime") > -1)
                //{
                //    isInheritField = true; // 继承基类字段
                //    attrList.Add("Insert = false"); // 非插入字段
                //}

                //if (column.Nullable == 0)
                //{
                //    // 允许Null值
                //    attrList.Add("Nullable = false");
                //}

                //if (!string.IsNullOrEmpty(column.DefaultValue))
                //{
                //    // 默认值
                //    attrList.Add($"Default = {column.DefaultValue}");
                //}

                //// 数据类型
                //attrList.Add($"DataType = \"{column.ReaderType}\"");

                //if (attrList.Count > 0)
                //{
                //    fieldAttribute = string.Join(",", attrList.ToArray());
                //    fieldProperty = $"[Column({fieldAttribute})]";
                //}

                //if (!isInheritField && column.Nullable == 0)
                //{
                //    var description = column.Comment?.Split('：')[0];
                //    // 必填字段
                //    requiredAttribute = $"[Required(ErrorMessage = \"{description}不能为空\")]";
                //}

                // 可查询字段，字符串长度大于-1的字段输出特性
                //if (isEntityAttribute && column.Queryable == 1 && (column.Length > -1))
                //{ }
                //if (!string.IsNullOrEmpty(fieldProperty))
                //{
                //    sb.AppendLine($"{fieldProperty}");
                //}
                //if (!string.IsNullOrEmpty(requiredAttribute))
                //{
                //    sb.AppendLine($"{requiredAttribute}");
                //}
                //if (column.Length > 0 && column.ColumnType == "string")
                //{
                //    if (column.Nullable == 1)
                //    {
                //        sb.AppendLine($"[StringLength({column.Length})]");
                //    }
                //    else
                //    {
                //        sb.AppendLine($"[StringLength({column.Length}, ErrorMessage = \"{{0}}必须至少包含{{2}}个字符。\", MinimumLength = 2)]");
                //    }
                //}

                #endregion

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"1）生成实体代码CS文件输出错误", ex);
                throw;
            }
        }

        /// <summary>
        /// 开始创建视图实体CS文件
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>

        private void CreateViewModelFile(string selectPath, List<Views> tableList, List<Columns> columnList)
        {
            if (tableList == null) return;

            try
            {
                string viewPath = $"{selectPath}\\Model\\Views\\"; // 视图数据对象
                FileHelper.FilePathCheck(viewPath);

                var spaceName = txtSpaceName.Text.Trim();
                var modelSpaceName = spaceName + ".Model";
                StringBuilder sb = new();

                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 视图名
                    var tableDesc = tableName; // 视图描述
                    var tableViewName = tableName!.ToSingularModelName(); // 视图实体名称
                    var viewFilePath = $"{viewPath}{tableViewName}.cs";

                    // 视图列项数据
                    var tableColumn = columnList.Where(entity => entity.TableName == tableName).ToList();

                    #region Model 实体数据对象

                    sb = new StringBuilder();

                    #region 引用文件

                    // 允许输出SqlSugar实体特性
                    if (isSqlSugarAttribute)
                    {
                        sb.AppendLine($"using SqlSugar;");
                    }

                    sb.AppendLine();

                    #endregion

                    #region 命名空间

                    sb.AppendLine($"namespace {modelSpaceName}.Views");

                    #endregion

                    sb.AppendLine("{");

                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {tableDesc}视图实体");
                    sb.AppendLine($"{tabOne}/// </summary>");

                    // 允许输出SqlSugar实体特性
                    if (isSqlSugarAttribute)
                    {
                        sb.AppendLine($"{tabOne}[SugarTable(\"{tableName}\")]");
                    }

                    sb.AppendLine($"{tabOne}public class {tableViewName}");

                    sb.AppendLine($"{tabOne}{{");

                    #region 构造函数

                    sb.AppendLine($"{tabTwo}public {tableViewName}()");
                    sb.AppendLine($"{tabTwo}{{");
                    sb.AppendLine($"{tabTwo}}}");
                    sb.AppendLine(" ");

                    #endregion

                    #region 实体属性

                    foreach (var column in tableColumn)
                    {
                        if (column == null)
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(column.Name))
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(column.DataType))
                        {
                            continue;
                        }

                        var columnName = column.Name; // 列名
                        var columnDesc = column.Comment?.Replace(":", "："); // 列描述【列基本描述：枚举描述】
                        columnDesc = columnDesc?.Replace("\n", ""); // 处理换行符
                        if (string.IsNullOrEmpty(columnDesc)) columnDesc = columnName;
                        var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                        string? strType = GetTypeMethod(column.DataType);
                        if (column.DataType.ToLower() == "date")
                        {
                            strType = frameworkVersion == 2 ? "DateOnly" : "DateTime"; // 日期 Date
                        }
                        else if (column.DataType.ToLower() == "time")
                        {
                            strType = frameworkVersion == 2 ? "TimeOnly" : "DateTime"; // 时间 Time
                        }

                        sb.AppendLine($"{tabTwo}/// <summary>");
                        sb.AppendLine($"{tabTwo}/// {columnDesc}");
                        sb.AppendLine($"{tabTwo}/// </summary>");

                        #region Column特性

                        var customColumnName = GetColumnName(columnName);
                        if (columnName != customColumnName)
                        {
                            sb.AppendLine($"{tabTwo}[Column(\"{columnName}\")]");
                            if (isSqlSugarAttribute)
                            {
                                sb.AppendLine($"{tabTwo}[SugarColumn(ColumnName=\"{columnName}\")]");
                            }
                            columnName = customColumnName;
                        }

                        #endregion

                        #region 输出属性

                        //  && strType != "string"
                        if (frameworkVersion == 2)
                        {
                            if (column?.IsPK == 0 && column.Nullable == 1) strType += "?";
                            if (strType == "string" && column!.Nullable == 0) strType += "?";
                        }

                        sb.AppendLine($"{tabTwo}public {strType} {columnName} {{ get; set; }}");

                        #endregion

                        sb.AppendLine();
                    }

                    #endregion

                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine("}");

                    File.WriteAllText(viewFilePath, sb.ToString());

                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"1.2）生成视图实体代码CS文件输出错误", ex);
                throw;
            }
        }

        /// <summary>
        /// 根据数据库类型映射数据库字段C#类型
        /// </summary>
        /// <param name="dataType">字段数据类型</param>
        /// <returns></returns>
        private static string? GetTypeMethod(string dataType)
        {
            // 数据库类型
            DBType dbType = (DBType)Enum.Parse(typeof(DBType), DbConfig?.DBType!);

            string? strType;
            switch (dbType)
            {
                case DBType.SqlServer:
                    Global.Dict_SqlServer_CSharpType.TryGetValue(dataType, out strType);
                    break;
                case DBType.MySql:
                    Global.Dict_MySql_CSharpType.TryGetValue(dataType, out strType);
                    break;
                case DBType.SQLite:
                    Global.Dict_Sqlite_CSharpType.TryGetValue(dataType, out strType);
                    break;
                default:
                    throw new ArgumentException("未知数据库类型！");
            }

            return strType;
        }

        #endregion

        #region 2）生成前端代码Html文件

        /// <summary>
        /// 是否是不处理的字段
        /// </summary>
        /// <param name="column">字段列项数据</param>
        /// <returns></returns>
        private static bool NoHandlerColumn(Columns column)
        {
            return column.IsPK == 1
            //|| column.Name.IndexOf("CreatorId") > -1
            //|| column.Name.IndexOf("CreateTime") > -1
            //|| column.Name.IndexOf("LastModifierId") > -1
            //|| column.Name.IndexOf("LastModifyTime") > -1
            //|| column.Name.IndexOf("ModifierId") > -1
            //|| column.Name.IndexOf("ModifiedTime") > -1
            ;
        }

        /// <summary>
        /// 是否是树结构对象
        /// </summary>
        /// <param name="column">字段列项数据</param>
        /// <returns></returns>
        private static bool IsTree(List<Columns> columns)
        {
            foreach (var column in columns)
            {
                if (column.Name!.ToLower().Contains("pid")
                || column.Name!.ToLower().Contains("parentid"))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 是否有Disabled列
        /// </summary>
        /// <param name="columns">字段列项数据</param>
        /// <returns></returns>
        private static bool HasDisabled(List<Columns> columns)
        {
            foreach (var column in columns)
            {
                if (column.Name!.ToLower().Contains("disabled"))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 开始创建生成表示层代码Html文件
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        private void CreateHtmlFile(string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            #region 命名空间检查

            var rootSpaceName = this.txtSpaceName.Text.Trim();
            if (string.IsNullOrEmpty(rootSpaceName))
            {
                MessageBox.Show("根命名空间为空！");
                return;
            }

            var modelSpaceName = $"{rootSpaceName}.Model.Models"; // 实体文件命名空间
            var dtoSpaceName = $"{rootSpaceName}.Model.Dtos"; // 实体文件命名空间
            var areaRootSpaceName = $"{rootSpaceName}.Web.Areas"; // 区域根命名空间

            var enableLogging = RefMaterial?.EnableLogging ?? false;
            var enableCaching = RefMaterial?.EnableCaching ?? false;
            var efContext = RefMaterial?.EfContext;

            #endregion

            #region 检查区域根目录

            var areaRootPath = $"{selectPath}\\Areas\\"; // 区域根目录

            FileHelper.FilePathCheck(areaRootPath);

            #endregion

            try
            {
                #region 区域名称汇总

                Dictionary<string, string> areaList = new Dictionary<string, string>();

                foreach (var table in tableList)
                {
                    var s = table.Name.Split('_')[0];

                    if (!areaList.ContainsKey(s))
                    {
                        areaList.Add(s, s);
                    }
                }

                #endregion

                StringBuilder sb = new();

                foreach (KeyValuePair<string, string> keyValue in areaList)
                {
                    #region 检查区域及子目录

                    var title = keyValue.Value;
                    var areaName = title.ToUpperFirst(); // 区域名称

                    var areaPath = Path.Combine($"{areaRootPath}", $"{areaName}\\");
                    FileHelper.FilePathCheck(areaPath);

                    var viewsPath = Path.Combine($"{areaPath}", $"Views\\");
                    FileHelper.FilePathCheck(viewsPath);

                    var filePath = string.Empty;

                    #endregion

                    // 表列项数据
                    var tables = tableList.Where(entity => entity.Name.StartsWith(title)).ToList();

                    foreach (var table in tables)
                    {
                        var tableName = table.Name; // 表名
                        if (table.Comment == null) continue;
                        var tableDesc = table.Comment.Replace(":", "："); // 表描述
                        //var tableViewName = tableName.ToSingularModelName(); // 表实体名称
                        //if (isSingularEntity) tableViewName = tableViewName;
                        var tableModelName = tableName.ToSingularModelName(); // 表实体名称
                        var controllerName = GetControllerName(tableName); // 控制器名称
                        if (!string.IsNullOrEmpty(controllerName) && !string.IsNullOrEmpty(areaName))
                            controllerName = controllerName.Replace(areaName, ""); // 控制器名去掉前面的去域名
                        var lowerTableName = tableModelName.ToLower(); // 小写表名
                        var baseTableDesc = tableDesc.Split('：')[0]; // 表基本描述【描述中冒号前面的部分】
                        filePath = $"{viewsPath}\\{controllerName}\\Index.cshtml";
                        FileHelper.FilePathCheck(filePath);

                        if (baseTableDesc == tableName)
                        {
                            baseTableDesc = $"{{{baseTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                        }

                        var primaryKey = "Id"; // 主键
                        var primaryKeyType = "uniqueidentifier"; // Guid类型
                        var primaryKeyObjectName = primaryKey;
                        var primaryKeyObjectDesc = "";

                        //var dateInput = false; // 是否有日期输入字段
                        var tableColumn = columnList
                            .Where(entity => entity.TableName == tableName).ToList();
                        var columnLength = tableColumn.Count;

                        sb = new StringBuilder();

                        sb.AppendLine($"@using {dtoSpaceName}");
                        sb.AppendLine($"@using {modelSpaceName}");
                        sb.AppendLine($"@model IEnumerable<{tableModelName}>");
                        sb.AppendLine($"");
                        sb.AppendLine($"@{{");
                        sb.AppendLine($"{tabOne}//ViewBag.Title = \"{baseTableDesc}管理\";");
                        sb.AppendLine($"{tabOne}Layout = \"~/Views/Shared/_Layout.cshtml\";");
                        sb.AppendLine($"}}");
                        sb.AppendLine($"");
                        sb.AppendLine($"<div class=\"row-fluid\" id=\"content-wrapper\">");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabOne}<!-- 中间内容展示区域 -->");
                        //sb.AppendLine($"{tabOne}<div class=\"col-12 col-md-12 col-lg-12\">");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTwo}<div class=\"page-header\">");
                        //sb.AppendLine($"{tabTre}<h2 class=\"pull-left\">");
                        //sb.AppendLine($"{tabTre}    <i class=\"glyphicon glyphicon-list\"></i>");
                        //sb.AppendLine($"{tabTre}    <span>@ViewBag.Title</span>");
                        //sb.AppendLine($"{tabTre}</h2>");
                        //sb.AppendLine($"{tabTre}<div class=\"pull-right\">");
                        //sb.AppendLine($"{tabTre}    <ul class=\"breadcrumb\">");
                        //sb.AppendLine($"{tabTre}        <li>");
                        //sb.AppendLine($"{tabTre}            <a href=\"#\"><i class=\"glyphicon glyphicon-home\"></i>首页</a>");
                        //sb.AppendLine($"{tabTre}        </li>");
                        ////sb.AppendLine($"{tabTre}        <li class=\"separator\">");
                        ////sb.AppendLine($"{tabTre}            <i class=\"fa fa-angle-right\"></i>");
                        ////sb.AppendLine($"{tabTre}        </li>");
                        ////sb.AppendLine($"{tabTre}        <li class=\"active\">@ViewBag.Title</li>");
                        //sb.AppendLine($"{tabTre}@for (int i = 0; i < ViewBag.MapName.Length; i++)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    <li class=\"separator\">");
                        //sb.AppendLine($"{tabTre}	<i class=\"fa fa-angle-right\"></i>");
                        //sb.AppendLine($"{tabTre}    </li>");
                        //sb.AppendLine($"{tabTre}    @if (i == ViewBag.MapName.Length - 1)");
                        //sb.AppendLine($"{tabTre}    {{");
                        //sb.AppendLine($"{tabTre}	<li class=\"active\">@ViewBag.MapName[i]</li>");
                        //sb.AppendLine($"{tabTre}    }}");
                        //sb.AppendLine($"{tabTre}    else");
                        //sb.AppendLine($"{tabTre}    {{");
                        //sb.AppendLine($"{tabTre}	<li>@ViewBag.MapName[i]</li>");
                        //sb.AppendLine($"{tabTre}    }}");
                        //sb.AppendLine($"{tabTre}}}");

                        //sb.AppendLine($"{tabTre}    </ul>");
                        //sb.AppendLine($"{tabTre}</div>");
                        //sb.AppendLine($"{tabTwo}</div>");

                        sb.AppendLine($"{tabOne}@await Component.InvokeAsync(\"PageHeader\")");
                        sb.AppendLine($"");

                        sb.AppendLine($"{tabOne}<div id=\"toolbar\">");
                        sb.AppendLine($"{tabTwo}<div class=\"form-inline\" role=\"form\">");
                        sb.AppendLine($"{tabTwo}    <form class=\"form-inline form-toolbar\">");
                        sb.AppendLine($"{tabTwo}        <div class=\"form-group\">");
                        sb.AppendLine($"{tabTwo}            <input name=\"search\" class=\"form-control form-control-sm\" type=\"text\" placeholder=\"搜索\">");

                        if (columnLength > 10)
                        {
                            sb.AppendLine($"{tabTre}            <div class=\"input-group input-group-sm\">");
                            sb.AppendLine($"{tabTre}                <input id=\"startDate\" name=\"startDate\" class=\"form-control form-control-sm\" type=\"date\" style=\"margin-right: 0 !important;\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"开始日期\" />");
                            sb.AppendLine($"{tabTre}                <div class=\"input-group-prepend\">");
                            sb.AppendLine($"{tabTre}                    <div class=\"input-group-text form-control-sm\">至</div>");
                            sb.AppendLine($"{tabTre}                </div>");
                            sb.AppendLine($"{tabTre}                <input id=\"endDate\" name=\"endDate\" class=\"form-control form-control-sm\" type=\"date\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"结束日期\" />");
                            sb.AppendLine($"{tabTre}            </div>");
                        }

                        sb.AppendLine($"{tabTwo}        </div>");
                        sb.AppendLine($"{tabTwo}    </form>");
                        sb.AppendLine($"{tabTwo}    <button id=\"remove\" class=\"btn btn-sm btn-danger\" disabled>");
                        sb.AppendLine($"{tabTwo}        <i class=\"glyphicon glyphicon-remove\"></i>批量删除");
                        sb.AppendLine($"{tabTwo}    </button>");
                        sb.AppendLine($"{tabTwo}    <button id=\"btnAdd\" class=\"btn btn-sm btn-primary\">");
                        sb.AppendLine($"{tabTwo}        <i class=\"glyphicon glyphicon-plus\"></i>添加{baseTableDesc}");
                        sb.AppendLine($"{tabTwo}    </button>");
                        //sb.AppendLine($"{tabTre}    <div class=\"btn-group\" role=\"group\" aria-label=\"query group\">");
                        //sb.AppendLine($"{tabTre}        <button id=\"btnSearch\" class=\"btn btn-sm btn-primary\" style=\"margin-right: 0!important;\">");
                        //sb.AppendLine($"{tabTre}            <i class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></i>查询");
                        //sb.AppendLine($"{tabTre}        </button>");
                        //sb.AppendLine($"{tabTre}        <button id=\"btnClear\" type=\"reset\" class=\"btn btn-secondary btn-sm\" title=\"清空查询条件\">");
                        //sb.AppendLine($"{tabTre}            <i class=\"glyphicon glyphicon-trash\" aria-hidden=\"true\"></i>");
                        //sb.AppendLine($"{tabTre}        </button>");
                        //sb.AppendLine($"{tabTre}    </div>");

                        sb.AppendLine($"{tabTwo}    @await Html.PartialAsync(\"~/Views/Shared/Buttons/_ToolbarQueryGroupWithExport.cshtml\")");

                        //sb.AppendLine($"{tabTre}    <button id=\"btnRandomData\" class=\"btn btn-sm btn-primary\">");
                        //sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-list\"></i>填充数据");
                        //sb.AppendLine($"{tabTre}    </button>");
                        sb.AppendLine($"{tabTwo}</div>");
                        sb.AppendLine($"{tabOne}</div>");
                        sb.AppendLine($"");
                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"{tabOne}<table id=\"{lowerTableName}-table\" class=\"table table-bordered table-striped table-sm table-hover\" data-buttons-prefix=\"btn-sm btn\" data-toolbar=\"#toolbar\"></table>");
                        }
                        else
                        {
                            sb.AppendLine($"{tabOne}<table id=\"{lowerTableName}-table\" class=\"table table-bordered table-striped table-sm table-hover\" data-buttons-prefix=\"btn-sm btn\" data-toolbar=\"#toolbar\"></table>");
                        }
                        sb.AppendLine($"");
                        sb.AppendLine($"</div>");
                        sb.AppendLine($"");
                        sb.AppendLine($"</div>");
                        sb.AppendLine($"");
                        sb.AppendLine($"<!-- {baseTableDesc}编辑模态窗体 //-->");
                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"<div class=\"modal fade\" id=\"editModel\" tabindex=\"-1\" role=\"dialog\" data-backdrop=\"static\" data-keyboard=\"false\" aria-labelledby=\"editModelLabel\" aria-hidden=\"true\">");
                        }
                        else
                        {
                            sb.AppendLine($"<div class=\"modal fade\" id=\"editModel\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\" aria-labelledby=\"editModelLabel\" aria-hidden=\"true\">");
                        }
                        sb.AppendLine($"{tabOne}<div class=\"modal-dialog modal-dialog-scrollable modal-dialog-centered\" role=\"document\">");
                        sb.AppendLine($"{tabTwo}<div class=\"modal-content\">");
                        sb.AppendLine($"{tabTre}<div class=\"modal-header\">");
                        sb.AppendLine($"{tabTre}    <h5 class=\"modal-title\" id=\"editModelLabel\">{baseTableDesc}编辑</h5>");
                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">");
                            sb.AppendLine($"{tabTre}        <span aria-hidden=\"true\">&times;</span>");
                            sb.AppendLine($"{tabTre}    </button>");
                        }
                        else
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button>");
                        }
                        sb.AppendLine($"{tabTre}</div>");
                        sb.AppendLine($"{tabTre}<div class=\"modal-body\">");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    <form class=\"form-horizontal\">");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述【列基本描述：枚举描述】
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            if (column.IsPK == 1)
                            {
                                primaryKey = columnName;
                                primaryKeyType = column.DataType;
                                primaryKeyObjectName = primaryKey;
                                primaryKeyObjectDesc = column.Comment;
                            }

                            var required = "";

                            if (column.IsPK == 0 && column.Nullable == 0 && column.DataType!.ToLower() != "int")
                            {
                                required = " required";
                            }

                            // 一些特殊的字段需要添加默认值
                            //var defaultValue = "";
                            //if (!string.IsNullOrEmpty(defaultValue))
                            //{
                            //    defaultValue = defaultValue.Replace("((", "").Replace("))", "");
                            //}
                            //if (column.DataType == "datetime" && !string.IsNullOrEmpty(defaultValue))
                            //{
                            //    defaultValue = DateTime.Now.ToString("yyyy-MM-dd");
                            //}
                            //if (column.DataType == "int")
                            //{
                            //    defaultValue = Guid.Empty.ToString();
                            //}

                            //if (column.Queryable == 1)
                            //{
                            if (NoHandlerColumn(column))
                            {
                                //sb.AppendLine($"{tabTre}        <input type=\"hidden\" asp-for=\"{columnName}\" />");
                                sb.AppendLine($"{tabTre}        <input type=\"hidden\" id=\"txt{columnName}\" name=\"txt{columnName}\" />");
                            }
                            else
                            {
                                //var datepicker = "";
                                //if (column.DataType == "datetime")
                                //{
                                //    dateInput = true; // 有日期输入字段
                                //    datepicker = " datepicker";
                                //}

                                var rightTwoLetter = columnName.Length > 2 ? columnName.Substring(columnName.Length - 2, 2).ToLower() : columnName.ToLower();

                                if (rightTwoLetter == "id")
                                {
                                    //sb.AppendLine($"{tabTre}        <input type=\"hidden\" asp-for=\"{columnName}\" />");
                                    sb.AppendLine($"{tabTre}        <input type=\"hidden\" id=\"txt{columnName}\" name=\"txt{columnName}\" />");
                                }
                                else
                                {
                                    if (columnDesc.Contains("：") && (column.DataType!.Contains("int") || column.DataType!.Contains("int"))) // 有枚举描述，Razor
                                    {
                                        sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                        //sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm\"></label>");
                                        sb.AppendLine($"{tabTre}            <label for=\"txt{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\">{baseColumnDesc}</label>");
                                        //sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm\"></label>");
                                        sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                        sb.AppendLine($"{tabTre}                <input id=\"txt{columnName}\" name=\"txt{columnName}\" type=\"number\" class=\"form-control form-control-sm\" />");
                                        //sb.AppendLine($"{tabTre}                @Html.DropDownList(\"txt{columnName}\", new SelectList(ViewBag.DropDownCacheList, \"Id\", \"Name\", Model.{columnName}), new {{ @class = \"form-control form-control-sm\" }})");
                                        //sb.AppendLine($"{tabTre}                <select asp-for=\"{columnName}\" class=\"form-control form-control-sm\" asp-items=\"Html.GetEnumSelectList<Enum{columnName}>()\"></select>");
                                        sb.AppendLine($"{tabTre}            </div>");
                                        sb.AppendLine($"{tabTre}        </div>");
                                    }
                                    else
                                    {
                                        if (column.DataType!.Contains("char") && (column.Length >= 255 || column.Length == -1) || column.DataType!.Contains("text"))
                                        {
                                            // 长文本字段varchar或nvarchar，长度大于等于255
                                            sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                            sb.AppendLine($"{tabTre}            <label for=\"txt{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\">{baseColumnDesc}</label>");
                                            //sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm\"></label>");
                                            sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                            sb.AppendLine($"{tabTre}                <textarea id=\"txt{columnName}\" name=\"txt{columnName}\" class=\"form-control form-control-sm\"></textarea>");
                                            //sb.AppendLine($"{tabTre}                <textarea asp-for=\"{columnName}\" class=\"form-control form-control-sm\"></textarea>");
                                            //sb.AppendLine($"{tabTre}                <span asp-validation-for=\"{columnName}\" class=\"text-danger\"></span>");
                                            sb.AppendLine($"{tabTre}            </div>");
                                            sb.AppendLine($"{tabTre}        </div>");
                                        }
                                        else
                                        {
                                            string objType = "type=\"text\" ";
                                            if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                                            {
                                                objType = "type=\"number\" ";
                                            }

                                            sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                            //sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm\"></label>");
                                            sb.AppendLine($"{tabTre}            <label for=\"txt{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\">{baseColumnDesc}</label>");
                                            sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                            //sb.AppendLine($"{tabTre}                <input asp-for=\"{columnName}\" class=\"form-control form-control-sm\" />");
                                            //sb.AppendLine($"{tabTre}                <span asp-validation-for=\"{columnName}\" class=\"text-danger\"></span>");
                                            sb.AppendLine($"{tabTre}                <input id=\"txt{columnName}\" name=\"txt{columnName}\" {objType}class=\"form-control form-control-sm\" />");
                                            sb.AppendLine($"{tabTre}            </div>");
                                            sb.AppendLine($"{tabTre}        </div>");
                                        }
                                    }
                                }
                            }

                            //}else{}

                            if ((column.DataType!.Contains("char") && column.Length == -1)
                                || column.DataType!.Contains("text") || column.DataType!.Contains("blob"))
                            {
                                // 长文本字段text,ntext或varchar(max),nvarchar(max)
                                sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                //sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm\"></label>");
                                sb.AppendLine($"{tabTre}            <label asp-for=\"txt{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\">{baseColumnDesc}</label>");
                                sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                sb.AppendLine($"{tabTre}                <textarea asp-for=\"txt{columnName}\" name=\"txt{columnName}\" class=\"form-control form-control-sm\"></textarea>");
                                sb.AppendLine($"{tabTre}                <span asp-validation-for=\"txt{columnName}\" class=\"text-danger\"></span>");
                                sb.AppendLine($"{tabTre}            </div>");
                                sb.AppendLine($"{tabTre}        </div>");
                            }

                            //sb.AppendLine($"{tabTre}        <input type=\"hidden\" asp-for=\"{columnName}\" />");
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    </form>");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}</div>");
                        sb.AppendLine($"{tabTre}<div class=\"modal-footer\">");
                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn btn-sm btn-secondary\" data-dismiss=\"modal\">");
                        }
                        else
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn btn-sm btn-secondary\" data-bs-dismiss=\"modal\">");
                        }
                        sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-floppy-remove\" aria-hidden=\"true\"></i>关闭");
                        sb.AppendLine($"{tabTre}    </button>");
                        sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn btn-sm btn-primary\" id=\"btnSave\">");
                        sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-floppy-saved\" aria-hidden=\"true\"></i>保存");
                        sb.AppendLine($"{tabTre}    </button>");
                        sb.AppendLine($"{tabTre}</div>");
                        sb.AppendLine($"{tabTwo}</div>");
                        sb.AppendLine($"{tabOne}</div>");
                        sb.AppendLine($"</div>");
                        sb.AppendLine($"");
                        sb.AppendLine($"@section Scripts {{");
                        sb.AppendLine($"{tabOne}@{{await Html.RenderPartialAsync(\"_ValidationScriptsPartial\");}}");
                        sb.AppendLine($"");

                        //sb.AppendLine($"{tabOne}<link href=\"~/css/tablelist.css\" rel=\"stylesheet\" />");
                        //sb.AppendLine($"{tabOne}<link href=\"~/css/task.css\" rel=\"stylesheet\" />");

                        sb.AppendLine($"");
                        sb.AppendLine($"<style type=\"text/css\">");
                        sb.AppendLine($"        td {{");
                        sb.AppendLine($"            text-overflow: ellipsis;");
                        sb.AppendLine($"            white-space: nowrap;");
                        sb.AppendLine($"            overflow: hidden;");
                        sb.AppendLine($"            word-break: keep-all;");
                        sb.AppendLine($"        }}");
                        sb.AppendLine($"</style>");

                        //sb.AppendLine($"");

                        //sb.AppendLine($"{tabOne}@Scripts.Render(\"~/bundles/jqueryval\")");
                        //sb.AppendLine($"{tabOne}@Scripts.Render(\"~/bundles/bootstraptable\")");

                        //if (dateInput)
                        //{
                        //    // 有日期输入字段
                        //    sb.AppendLine($"{tabOne}@Scripts.Render(\"~/bundles/datetimepicker\")");
                        //}

                        //sb.AppendLine($"{tabOne}@Scripts.Render(\"~/bundles/ctd\")");
                        //sb.AppendLine($"{tabOne}@*@Scripts.Render(\"~/bundles/{lowerTableName}\")*@"); // 当前页Jscript脚本

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabOne}<script type=\"text/javascript\">");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}var $table = $('#{lowerTableName}-table'),");
                        sb.AppendLine($"{tabTre}$remove = $('#remove'),");
                        sb.AppendLine($"{tabTre}selections = [],");
                        sb.AppendLine($"{tabTre}key = '{primaryKey}';");
                        sb.AppendLine($"");

                        //var defaultPrimaryKeyValue = "0";
                        //if (primaryKeyType == "int")
                        //{
                        //    sb.AppendLine($"{tabTwo}var defaultGuid = '00000000-0000-0000-0000-000000000000';");
                        //}

                        //if (primaryKeyType == "int")
                        //{
                        //    defaultPrimaryKeyValue = "0";
                        //}

                        //sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}var pageNumber = 1, pageSize = 10;");
                        sb.AppendLine($"{tabTwo}var pageListUrl = \"/{areaName}/{controllerName}/PageList\";");
                        //sb.AppendLine($"{tabTwo}var circleModalId = \"circleModal\", $circleModal = null; // 圆形进度条窗体及对象");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}$(function () {{");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$table = $('#{lowerTableName}-table'),");
                        sb.AppendLine($"{tabTre}    $remove = $('#remove');");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$(\"#btnAdd\").on(function () {{");
                        sb.AppendLine($"");

                        sb.AppendLine($"{tabTre}    // 默认Guid类型字段初始化处理");

                        foreach (var column in tableColumn)
                        {
                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment; // 列描述

                            if (column.DataType == "int")
                            {
                                sb.AppendLine($"{tabTre}    $(\"#txt{columnName}\").val(defaultGuid); // {columnDesc}");
                            }
                        }

                        //sb.AppendLine($"{tabTre}    $(\"#Name\").focus();");

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    $(\"#editModelLabel\").html(\"{baseTableDesc}信息添加\");");
                        sb.AppendLine($"{tabTre}    $('#editModel').modal('toggle');");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}initTable();");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}// 关键词查询");
                        sb.AppendLine($"{tabTre}$('input[name=\"search\"]').off('keydown').on('keydown', function (e) {{");
                        sb.AppendLine($"{tabTre}    if (e.code == \"Enter\") {{");
                        sb.AppendLine($"{tabTre}        pageNumber = 1;");
                        sb.AppendLine($"{tabTre}        refreshTable();");
                        sb.AppendLine($"{tabTre}    }}");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}	    // 查询按钮点击事件");
                        sb.AppendLine($"{tabTre}            $('#btnSearch').off('click').on('click', function (e) {{");
                        sb.AppendLine($"{tabTre}                pageNumber = 1;");
                        sb.AppendLine($"{tabTre}                refreshTable();");
                        sb.AppendLine($"{tabTre}            }});");
                        sb.AppendLine($"");

                        //if (dateInput)
                        //{
                        //    sb.AppendLine($"{tabTre}$(\".datepicker\").datetimepicker({{");
                        //    sb.AppendLine($"{tabTre}    language: \"zh-CN\",");
                        //    sb.AppendLine($"{tabTre}    autoclose: true,//选中之后自动隐藏日期选择框");
                        //    sb.AppendLine($"{tabTre}    clearBtn: true,//清除按钮");
                        //    sb.AppendLine($"{tabTre}    //todayBtn: true,//今日按钮");
                        //    sb.AppendLine($"{tabTre}    minView: \"month\", //选择日期后，不会再跳转去选择时分秒");
                        //    sb.AppendLine($"{tabTre}    format: \"yyyy-mm-dd\"//日期格式");
                        //    sb.AppendLine($"{tabTre}}});");
                        //}

                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}// 填充随机数据");
                        //sb.AppendLine($"{tabTre}$(\"#btnRandomData\").off('click').on('click', function () {{");
                        //sb.AppendLine($"{tabTre}    CTD.Modal.CircleMessage(circleModalId, \"数据填充操作正在进行中，请稍候...\");");
                        //sb.AppendLine($"{tabTre}    $(\"#\" + circleModalId).modal(\"toggle\");");
                        //sb.AppendLine($"{tabTre}    $.ajax({{");
                        //sb.AppendLine($"{tabTre}        url: '/{areaName}/{controllerName}/SqlBulkRandomData/?rnd=' + (Math.random() * 10),");
                        //sb.AppendLine($"{tabTre}        type: 'GET',");
                        //sb.AppendLine($"{tabTre}        data: {{ rnd: (Math.random() * 16) }},");
                        //sb.AppendLine($"{tabTre}        success: function (rst) {{");
                        //sb.AppendLine($"{tabTre}            $(\"#\" + circleModalId).modal(\"hide\");");
                        //sb.AppendLine($"{tabTre}            if (rst && rst.success) {{");
                        //sb.AppendLine($"{tabTre}                refreshTable();");
                        //sb.AppendLine($"{tabTre}                $.alert({{ title: '操作成功!', content: rst.message }});");
                        //sb.AppendLine($"{tabTre}            }} else {{");
                        //sb.AppendLine($"{tabTre}                modals.error(rst.message ?? rst.Message);");
                        //sb.AppendLine($"{tabTre}            }}");
                        //sb.AppendLine($"{tabTre}        }}");
                        //sb.AppendLine($"{tabTre}    }});");
                        //sb.AppendLine($"{tabTre}}});");

                        sb.AppendLine($"{tabTwo}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}// 刷新表格数据");
                        sb.AppendLine($"{tabTwo}function refreshTable() {{");
                        //sb.AppendLine($"{tabTre}$table.bootstrapTable({{ url: pageListUrl }});");
                        sb.AppendLine($"{tabTre}$table.bootstrapTable('refresh', {{ pageNumber: 1 }});");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}// 初始化表");
                        sb.AppendLine($"{tabTwo}function initTable() {{");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}//先销毁表格");
                        sb.AppendLine($"{tabTre}$table.bootstrapTable('destroy');");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$table.bootstrapTable({{");
                        sb.AppendLine($"{tabTre}    height: getHeight(),");
                        sb.AppendLine($"{tabTre}    method: 'get', // 请求方式（*）");
                        sb.AppendLine($"{tabTre}    dataType: \"json\", // 数据类型");
                        sb.AppendLine($"{tabTre}    url: pageListUrl, // 请求后台地址,");
                        sb.AppendLine($"{tabTre}    toolbar: '#toolbar', //工具按钮用哪个容器");
                        sb.AppendLine($"{tabTre}    theadClasses: 'thead-dark', // 表头样式");
                        sb.AppendLine($"{tabTre}    striped: true, // 使表格带有条纹");
                        sb.AppendLine($"{tabTre}    uniqueId: key, // 唯一标识");
                        sb.AppendLine($"{tabTre}    idField: key, // 标识哪个字段为id主键");
                        sb.AppendLine($"{tabTre}    pagination: true, // 在表格底部显示分页工具栏");
                        sb.AppendLine($"{tabTre}    pageSize: pageSize, // 分页大小");
                        sb.AppendLine($"{tabTre}    pageNumber: pageNumber, // 当前页码");
                        sb.AppendLine($"{tabTre}    pageList: [10, 20, 50, 100, 200, 500],");
                        sb.AppendLine($"{tabTre}    sidePagination: \"server\", //表格分页的位置");
                        sb.AppendLine($"{tabTre}    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder");
                        sb.AppendLine($"{tabTre}    //设置为limit可以获取limit, offset, search, sort, order");
                        sb.AppendLine($"{tabTre}    queryParamsType: \"undefined\",");
                        sb.AppendLine($"{tabTre}    queryParams: function queryParams(params) {{ //设置查询参数");
                        sb.AppendLine($"{tabTre}        var param = {{");
                        sb.AppendLine($"{tabTre}            pageNumber: params.pageNumber,");
                        sb.AppendLine($"{tabTre}            pageSize: params.pageSize,");
                        sb.AppendLine($"{tabTre}            title: $(\"input[name='search']\").val()");
                        sb.AppendLine($"{tabTre}        }};");
                        sb.AppendLine($"{tabTre}        pageNumber = params.pageNumber;");
                        sb.AppendLine($"{tabTre}        return param;");
                        sb.AppendLine($"{tabTre}    }},");
                        sb.AppendLine($"{tabTre}    columns: [");
                        sb.AppendLine($"{tabTre}        [");
                        sb.AppendLine($"{tabTre}            {{");
                        sb.AppendLine($"{tabTre}                field: 'checked',");
                        sb.AppendLine($"{tabTre}                checkbox: true");
                        sb.AppendLine($"{tabTre}            }}, {{");
                        sb.AppendLine($"{tabTre}                title: '序号',");
                        sb.AppendLine($"{tabTre}                field: 'RowNumber',");
                        sb.AppendLine($"{tabTre}                width: 60,");
                        sb.AppendLine($"{tabTre}                align: 'center',");
                        sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                        sb.AppendLine($"{tabTre}                	var options = $table.bootstrapTable('getOptions');");
                        sb.AppendLine($"{tabTre}                	return options.pageSize * (options.pageNumber - 1) + index + 1;");
                        sb.AppendLine($"{tabTre}                }}");
                        sb.AppendLine($"{tabTre}            }}, {{");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】                   

                            //if (column.Queryable == 1)//{//}

                            if (NoHandlerColumn(column))
                            {
                                // 去除字段
                            }
                            else
                            {
                                var rightTwoLetter = columnName.Length > 2 ? columnName.Substring(columnName.Length - 2, 2).ToLower() : columnName.ToLower();

                                if (rightTwoLetter == "id")
                                {
                                    // 尾部2个字符为ID的不显示
                                }
                                else
                                {
                                    sb.AppendLine($"{tabTre}                field: '{columnName}',");
                                    sb.AppendLine($"{tabTre}                title: '{baseColumnDesc}',");

                                    var tdWidth = 60; // 普通列宽带
                                    if (column.DataType == "datetime")
                                    {
                                        tdWidth = 105; // 日期列宽带
                                    }
                                    else
                                    {
                                        if (column.Length > 0)
                                        {
                                            tdWidth = 120;
                                        }
                                    }

                                    sb.AppendLine($"{tabTre}                width: {tdWidth},");
                                    sb.AppendLine($"{tabTre}                halign: 'center',");

                                    var align = "center";
                                    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                                    {
                                        align = "right"; // 数值型
                                    }
                                    else if (column.Length > 0)
                                    {
                                        align = "left"; // 字符型
                                    }

                                    sb.AppendLine($"{tabTre}                align: '{align}',");

                                    var formatter = "";
                                    if (column.DataType!.ToLower().Contains("char") && column.Length > 50)
                                    {
                                        formatter = "tipsFormatter"; // 字符型
                                    }

                                    if (column.DataType == "datetime") // 日期时间列表格式
                                    {
                                        if (bootstrapVersion == 4)
                                        {
                                            sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                                            sb.AppendLine($"{tabTre}                    return (value == null || value.length == 0) ? \"\" : value.toDateTimeString();");
                                            sb.AppendLine($"{tabTre}                }}");
                                        }
                                    }
                                    else if (column.DataType == "date") // 日期列表格式
                                    {
                                        sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                                        sb.AppendLine($"{tabTre}                    return (value == null || value.length == 0) ? \"\" : value.toDateString();");
                                        sb.AppendLine($"{tabTre}                }}");
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(formatter))
                                        {
                                            sb.AppendLine($"{tabTre}                formatter: {formatter}");
                                        }
                                    }

                                    sb.AppendLine($"{tabTre}            }}, {{");
                                }
                            }
                        }

                        foreach (var column in tableColumn.Where(s => s.Name == "State"))
                        {
                            sb.AppendLine($"{tabTre}                field: 'State',");
                            sb.AppendLine($"{tabTre}                title: '状态',");
                            sb.AppendLine($"{tabTre}                width: 60,");
                            sb.AppendLine($"{tabTre}                halign: 'center',");
                            sb.AppendLine($"{tabTre}                align: 'center',");
                            sb.AppendLine($"{tabTre}                formatter: stateFormatter");
                            sb.AppendLine($"{tabTre}            }}, {{");
                        }

                        sb.AppendLine($"{tabTre}                title: '操作',");
                        sb.AppendLine($"{tabTre}                width: 90,");
                        sb.AppendLine($"{tabTre}                halign: 'center',");
                        sb.AppendLine($"{tabTre}                align: 'center',");
                        sb.AppendLine($"{tabTre}                events: operateEvents,");
                        sb.AppendLine($"{tabTre}                formatter: operateFormatter");
                        sb.AppendLine($"{tabTre}            }}");
                        sb.AppendLine($"{tabTre}        ]");
                        sb.AppendLine($"{tabTre}    ],");
                        sb.AppendLine($"{tabTre}    formatLoadingMessage: function () {{");
                        sb.AppendLine($"{tabTre}        return \"请稍等，正在加载中...\";");
                        sb.AppendLine($"{tabTre}    }},");
                        sb.AppendLine($"{tabTre}    formatNoMatches: function () {{ //没有匹配的结果");
                        sb.AppendLine($"{tabTre}        return '无符合条件的记录';");
                        sb.AppendLine($"{tabTre}    }}");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}// sometimes footer render error.");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}setTimeout(function () {{");
                        sb.AppendLine($"{tabTre}    $table.bootstrapTable('resetView');");
                        sb.AppendLine($"{tabTre}    $('[data-toggle=\"tooltip\"]').tooltip();");
                        sb.AppendLine($"{tabTre}}}, 200);");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$table.on('check.bs.table uncheck.bs.table ' +");
                        sb.AppendLine($"{tabTre}    'check-all.bs.table uncheck-all.bs.table', function () {{");
                        sb.AppendLine($"{tabTre}        $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}        // save your data, here just save the current page");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}        selections = getIdSelections();");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}        // push or splice the selections if you want to save all data selections");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    }});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$remove.off('click').on('click', function () {{ // 批量删除");
                        sb.AppendLine($"{tabTre}    var ids = getIdSelections();");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"{tabTre}    $remove.prop('disabled', true);");
                            sb.AppendLine($"{tabTre}    BatchLogicalDelete(ids.toString()); // 批量逻辑删除");
                        }
                        else
                        {
                            //sb.AppendLine($"{tabTre}    $table.bootstrapTable('remove', {{");
                            //sb.AppendLine($"{tabTre}        field: key,");
                            //sb.AppendLine($"{tabTre}        values: ids");
                            //sb.AppendLine($"{tabTre}    }});");
                            sb.AppendLine($"{tabTre}    $remove.prop('disabled', true);");
                            sb.AppendLine($"{tabTre}    BatchDelete(ids.toString()); // 批量删除");
                        }

                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$(window).resize(function () {{");
                        sb.AppendLine($"{tabTre}    $table.bootstrapTable('resetView', {{");
                        sb.AppendLine($"{tabTre}        height: getHeight()");
                        sb.AppendLine($"{tabTre}    }});");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}// 获取选择项");
                        sb.AppendLine($"{tabTwo}function getIdSelections() {{");
                        sb.AppendLine($"{tabTre}return $.map($table.bootstrapTable('getSelections'), function (row) {{");
                        sb.AppendLine($"{tabTre}    return row[key];");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}// 操作内容格式化");
                        sb.AppendLine($"{tabTwo}function operateFormatter(value, row, index) {{");
                        //sb.AppendLine($"{tabTre}return [");
                        //sb.AppendLine($"{tabTre}    '<a class=\"edit\" href=\"javascript:void(0)\" title=\"修改{shortTableDesc}\">',");
                        //sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-edit\"></i>',");
                        //sb.AppendLine($"{tabTre}    '</a>  ',");
                        //sb.AppendLine($"{tabTre}    '<a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{shortTableDesc}\">',");
                        //sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                        //sb.AppendLine($"{tabTre}    '</a>'");
                        //sb.AppendLine($"{tabTre}].join('');");
                        sb.AppendLine($"{tabTre}var edit = ['<a class=\"edit\" href=\"javascript:void(0)\" title=\"修改{baseTableDesc}\">',");
                        sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-edit\"></i>',");
                        sb.AppendLine($"{tabTre}    '</a>'];");
                        sb.AppendLine($"");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"{tabTre}var enable = ['<a class=\"enable\" href=\"javascript:void(0)\" title=\"启用{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-ok\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"");
                            sb.AppendLine($"{tabTre}var disable = ['<a class=\"disable\" href=\"javascript:void(0)\" title=\"禁用{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-ban-circle\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"");
                            sb.AppendLine($"{tabTre}var remove = ['<a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"");
                            sb.AppendLine($"{tabTre}// 数据状态：0-正常；1-禁用；2-删除");
                            sb.AppendLine($"{tabTre}if (row.State == 0) {{");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(disable);");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(remove);");
                            sb.AppendLine($"{tabTre}}}");
                            sb.AppendLine($"{tabTre}if (row.State == 1) {{");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(enable);");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(remove);");
                            sb.AppendLine($"{tabTre}}}");
                            sb.AppendLine($"{tabTre}if (row.State == 2) {{");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(enable);");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(disable);");
                            sb.AppendLine($"{tabTre}}}");
                            sb.AppendLine($"");
                        }
                        else
                        {
                            // 已经在样式表中定义了图标的左右间距，因此，不用再添加空格
                            sb.AppendLine($"{tabTre}var remove = ['<a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"{tabTre}edit = edit.concat(remove);");
                        }

                        sb.AppendLine($"{tabTre}return edit.join('');");

                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}// 操作事件响应");
                        sb.AppendLine($"{tabTwo}window.operateEvents = {{");
                        sb.AppendLine($"{tabTre}'click .edit': function (e, value, row, index) {{");
                        sb.AppendLine($"{tabTre}    //alert('You click edit action, row: ' + JSON.stringify(row));");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    //debugger;");
                        sb.AppendLine($"{tabTre}    //console.info(\"编辑前获取行数据：\");");
                        sb.AppendLine($"{tabTre}    console.info(row);");
                        sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】                  

                            //if (column.Queryable == 1)
                            //{
                            //if (column.Name.IndexOf("State") > -1
                            //    //|| column.Name.IndexOf("CreatorId") > -1
                            //    //|| column.Name.IndexOf("CreateTime") > -1
                            //    //|| column.Name.IndexOf("LastModifierId") > -1
                            //    //|| column.Name.IndexOf("LastModifyTime") > -1
                            //    //|| column.Name.IndexOf("ModifierId") > -1
                            //    //|| column.Name.IndexOf("ModifiedTime") > -1
                            //    )
                            //{
                            //    sb.AppendLine($"{tabTre}    //$(\"#txt{columnName}\").val(row.{columnName}); // {columnDesc}");
                            //}
                            //else
                            //{}                    
                            //}
                            //else
                            //{
                            //    sb.AppendLine($"{tabTre}    //$(\"#txt{columnName}\").val(row.{columnName}); // {columnDesc}");
                            //}

                            //if (column.DataType == "datetime")
                            //{
                            //    dateInput = true; // 有日期输入字段
                            //}

                            sb.AppendLine($"{tabTre}    $(\"#txt{columnName}\").val(row.{columnName}); // {columnDesc}");

                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    $(\"#editModelLabel\").html(\"{baseTableDesc}信息修改\");");
                        sb.AppendLine($"{tabTre}    $('#editModel').modal('toggle');");
                        sb.AppendLine($"{tabTre}}},");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"		'click .enable': function (e, value, row, index) {{");
                            sb.AppendLine($"			Enable(row[key]); // 启用行数据");
                            sb.AppendLine($"		}}, 'click .disable': function (e, value, row, index) {{");
                            sb.AppendLine($"			Disable(row[key]); // 禁用行数据");
                        }
                        sb.AppendLine($"		'click .remove': function (e, value, row, index) {{");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"{tabTre}    LogicalDelete(row[key]); // 逻辑删除行数据");
                        }
                        else
                        {
                            //sb.AppendLine($"			$table.bootstrapTable('remove', {{");
                            //sb.AppendLine($"				field: key,");
                            //sb.AppendLine($"				values: [row[key]]");
                            //sb.AppendLine($"			}});");
                            sb.AppendLine($"			Delete(row[key]); // 删除行数据");
                        }

                        sb.AppendLine($"			}}");
                        sb.AppendLine($"		}};");

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}// 获取内容高度");
                        sb.AppendLine($"{tabTwo}function getHeight() {{");
                        sb.AppendLine($"{tabTre}var heightCorrection = 115;");
                        sb.AppendLine($"{tabTre}return $(window).height() - $('h2').outerHeight(true) - heightCorrection;");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 启用数据");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"");
                            sb.AppendLine($"function Enable(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要启用该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{areaName}/{controllerName}/Enable/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			//data: \"{{'id':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 禁用数据");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"");
                            sb.AppendLine($"function Disable(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要禁用该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{areaName}/{controllerName}/Disable/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			//data: \"{{'id':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 逻辑删除");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function LogicalDelete(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要逻辑删除该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{areaName}/{controllerName}/LogicalDelete/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			//data: \"{{'id':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 批量逻辑删除");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function BatchLogicalDelete(ids) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要批量逻辑删除这些{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{areaName}/{controllerName}/BatchLogicalDelete/\" + ids + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			//data: \"{{'ids':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                        }
                        else
                        {
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 物理删除数据");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function Delete(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要删除该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{areaName}/{controllerName}/Delete/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'id':'\" + id + \"'}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 批量物理删除");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function BatchDelete(ids) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要批量删除这些{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{areaName}/{controllerName}/BatchDelete/\" + ids + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'ids':'\" + ids + \"'}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                        }

                        sb.AppendLine($"{tabTwo}$(function () {{");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$('#editModel').on('hidden.bs.modal', function () {{ // 关闭模态窗体事件");
                        sb.AppendLine($"{tabTre}    $(\"#editModel form\")[0].reset();");
                        sb.AppendLine($"{tabTre}    $(\"#btnSave\").prop(\"disabled\", false); // 解除保存按钮禁用");
                        sb.AppendLine($"{tabTre}    $(\"#editModel form input[type='hidden']\").val(\"\");");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre} // 数据保存");
                        sb.AppendLine($"{tabTre}$(\"#btnSave\").off(\"click\").on(\"click\", function () {{");
                        sb.AppendLine($"");
                        sb.AppendLine($"Loading.Message(\"合同数据保存正在进行中，请稍候...\");");
                        sb.AppendLine($"");
                        sb.AppendLine($"//debugger;");
                        sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述                 

                            sb.AppendLine($"{tabTre}    var txt{columnName} = $(\"#txt{columnName}\").val(); // {columnDesc}");

                            ////if (column.Queryable == 1)
                            ////{
                            //if (column.Name.IndexOf("State") > -1
                            //    //|| column.Name.IndexOf("CreatorId") > -1
                            //    //|| column.Name.IndexOf("CreateTime") > -1
                            //    //|| column.Name.IndexOf("LastModifierId") > -1
                            //    //|| column.Name.IndexOf("LastModifyTime") > -1
                            //    //|| column.Name.IndexOf("ModifierId") > -1
                            //    //|| column.Name.IndexOf("ModifiedTime") > -1
                            //    )
                            //{
                            //    sb.AppendLine($"{tabTre}    //var txt{columnName} = $(\"#txt{columnName}\").val(); // {columnDesc}");
                            //}
                            //else
                            //{
                            //}
                            ////}
                            ////else
                            ////{
                            ////    sb.AppendLine($"{tabTre}    //var txt{columnName} = $(\"#txt{columnName}\").val(); // {columnDesc}");
                            ////}

                        }

                        #region MyRegion

                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    var txtID = $(\"#ID\").val(); // {shortTableDesc}ID");
                        //sb.AppendLine($"{tabTre}    //var txtOrganId = $(\"#OrganId\").val(); // 机构ID");
                        //sb.AppendLine($"{tabTre}    //var txtDepartmentId = $(\"#DepartmentId\").val(); // 部门ID");
                        //sb.AppendLine($"{tabTre}    var txtName = $(\"#Name\").val(); // {shortTableDesc}名称");
                        //sb.AppendLine($"{tabTre}    //var txtImage = $(\"#Image\").val(); // {shortTableDesc}图片");
                        //sb.AppendLine($"{tabTre}    var txtAddress = $(\"#Address\").val(); // {shortTableDesc}地址");
                        //sb.AppendLine($"{tabTre}    var txtCircuit = $(\"#Circuit\").val(); // {shortTableDesc}线路");
                        //sb.AppendLine($"{tabTre}    var txtProvinceId = $(\"#ProvinceId\").val(); // 所属省份，取自字典数据，统计用");
                        //sb.AppendLine($"{tabTre}    var txtRegionId = $(\"#RegionId\").val(); // 所属地区ID，取自字典数据");
                        //sb.AppendLine($"{tabTre}    var txtMapX = $(\"#MapX\").val(); // 地图坐标X");
                        //sb.AppendLine($"{tabTre}    var txtMapY = $(\"#MapY\").val(); // 地图坐标Y");
                        //sb.AppendLine($"{tabTre}    var txtQQMapUrl = $(\"#QQMapUrl\").val(); // 腾讯地图Url");
                        //sb.AppendLine($"{tabTre}    var txtAmapUrl = $(\"#AmapUrl\").val(); // 高德地图URL");
                        //sb.AppendLine($"{tabTre}    var txtBaiduMapUrl = $(\"#BaiduMapUrl\").val(); // 百度地图URL");
                        //sb.AppendLine($"{tabTre}    var txtClassroomNum = $(\"#ClassroomNum\").val(); // 教室数量");
                        //sb.AppendLine($"{tabTre}    var txtIntroduce = $(\"#Introduce\").val(); // {shortTableDesc}介绍");
                        //sb.AppendLine($"{tabTre}    var txtIntroduceUrl = $(\"#IntroduceUrl\").val(); // {shortTableDesc}介绍链接");
                        //sb.AppendLine($"{tabTre}    var txtPrice = $(\"#Price\").val(); // {shortTableDesc}租金费用");
                        //sb.AppendLine($"{tabTre}    var txtUseTime = $(\"#UseTime\").val(); // 启用时间");
                        //sb.AppendLine($"{tabTre}    var txtOutTime = $(\"#OutTime\").val(); // 停用时间");
                        //sb.AppendLine($"{tabTre}    var txtBeginTime = $(\"#BeginTime\").val(); // 营业时间");
                        //sb.AppendLine($"{tabTre}    var txtEndTime = $(\"#EndTime\").val(); // 截止时间");
                        //sb.AppendLine($"{tabTre}    //var txtSortNumber = $(\"#SortNumber\").val(); // 排序编号");
                        //sb.AppendLine($"{tabTre}    var txtRemark = $(\"#Remark\").val(); // {shortTableDesc}备注");
                        //sb.AppendLine($"{tabTre}    //var txtState = $(\"#State\").val(); // 数据状态：0-正常；1-禁用；2-删");
                        //sb.AppendLine($"{tabTre}    //var txtCreatorId = $(\"#CreatorId\").val(); // 创建人ID");
                        //sb.AppendLine($"{tabTre}    //var txtCreateTime = $(\"#CreateTime\").val(); // 创建时间");
                        //sb.AppendLine($"{tabTre}    //var txtModifierId = $(\"#ModifierId\").val(); // 编辑人ID");
                        //sb.AppendLine($"{tabTre}    //var txtModifiedTime = $(\"#ModifiedTime\").val(); // 编辑时间");
                        sb.AppendLine($"");

                        #endregion

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            //if (column.Queryable == 1)//{//}

                            if (NoHandlerColumn(column))
                            {
                                // 不处理
                            }
                            else
                            {
                                // 必填项
                                if (columnName == "Name" || column.Nullable == 0)
                                {
                                    var alertTitle = baseColumnDesc;
                                    if (alertTitle!.Contains("Name")) alertTitle += "名称";
                                    sb.AppendLine($"{tabTre}    if ( txt{columnName} == undefined || txt{columnName}.length == 0) {{");
                                    //sb.AppendLine($"{tabTre}        $.alert('请填写{baseColumnDesc}名称！', '操作提示');");
                                    sb.AppendLine($"{tabTre}        toastr.error('请填写{alertTitle}！');// 其它弹出方式影响focus");
                                    sb.AppendLine($"{tabTre}        $(\"#txt{columnName}\").focus();");
                                    sb.AppendLine($"{tabTre}        return;");
                                    sb.AppendLine($"{tabTre}    }}");
                                }
                            }
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"$(\"#btnSave\").prop(\"disabled\", \"disabled\"); // 禁用保存按钮，防止重复提交");
                        sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述                    

                            //if (column.Queryable == 1)//{//}

                            if (NoHandlerColumn(column))
                            {
                                // 不处理
                            }
                            else
                            {
                                // 数值项
                                if (column.Length > 0 && column.DataType!.Contains("int", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    sb.AppendLine($"{tabTre}    if (txt{columnName} == undefined || txt{columnName}.length == 0) {{");
                                    sb.AppendLine($"{tabTre}        txt{columnName} = \"0\";");
                                    sb.AppendLine($"{tabTre}    }}");
                                }
                            }
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    // 字符串输入超长处理");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            if (column.DataType!.ToLower().Contains("char") && column.Length > 0 && column.Length < 50)
                            {
                                sb.AppendLine($"{tabTre}    if (txt{columnName} && txt{columnName}.length > {column.Length}) {{");
                                sb.AppendLine($"{tabTre}        toastr.error('{baseColumnDesc}超过设定长度{column.Length}！');");
                                sb.AppendLine($"{tabTre}        $(\"#txt{columnName}\").focus();");
                                sb.AppendLine($"{tabTre}        return;");
                                sb.AppendLine($"{tabTre}    }}");
                            }
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    // 字符串中异常字符处理");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            // 文本字段检查异常字符
                            if (column.DataType!.Contains("char") || column.DataType!.Contains("text"))
                            {
                                // /'%7C%5C%5C%7C%5C/%7C%5C%22%7C%5C%7C%7C%3E%7C%3C%7C%5C*%7C%5C?%7C:/g
                                var matchString = "%2F'%7C%5C%5C%7C%5C%22%7C%5C%7C%7C%3E%7C%3C%7C%5C*%7C%5C%3F%2Fg";
                                matchString = HttpUtility.UrlDecode(matchString);
                                sb.AppendLine($"{tabTre}    if (txt{columnName} != undefined && txt{columnName}.length > 0) {{");
                                sb.AppendLine($"{tabTre}        txt{columnName} = txt{columnName}.replace({matchString}, \"\"); // {columnDesc}");
                                sb.AppendLine($"{tabTre}    }}");
                            }
                        }

                        sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    var strJson = \"{{\";");
                        sb.AppendLine($"{tabTre}    var obj = {{}};");
                        //sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            //if (NoHandlerColumn(column))
                            //{
                            //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\" + txt{columnName} + \",\"; // {columnDesc}");
                            //    }
                            //    else
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\\\"\" + txt{columnName} + \"\\\",\"; // {columnDesc}");
                            //    }
                            //}
                            //else
                            //{
                            //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\" + txt{columnName} + \",\"; // {columnDesc}");
                            //    }
                            //    else
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\\\"\" + txt{columnName} + \"\\\",\"; // {columnDesc}");
                            //    }
                            //}

                            //if (column.Queryable == 1)
                            //{
                            //}
                            //else
                            //{
                            //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                            //    {
                            //        sb.AppendLine($"{tabTre}    //strJson += \"\\\"{columnName}\\\":\" + txt{columnName} + \",\"; // {columnDesc}");
                            //    }
                            //    else
                            //    {
                            //        sb.AppendLine($"{tabTre}    //strJson += \"\\\"{columnName}\\\":\\\"\" + txt{columnName} + \"\\\",\"; // {columnDesc}");
                            //    }
                            //}

                            sb.AppendLine($"{tabTre}    obj.{columnName} = txt{columnName}; // {columnDesc}");
                        }

                        //sb.AppendLine($"{tabTre}    strJson += \"\/\"Id\\\":\/\"\" + txtID + \"\/\",\"; // {shortDesc}ID");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_OrganId\\\":\\\"\" + txtOrganId + \"\\\",\"; // 机构ID");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_DepartmentId\\\":\\\"\" + txtDepartmentId + \"\\\",\"; // 部门ID");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_Name\\\":\\\"\" + txtName + \"\\\",\"; // {shortTableDesc}名称");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_Image\\\":\\\"\" + txtImage + \"\\\",\"; // {shortTableDesc}图片");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_Address\\\":\\\"\" + txtAddress + \"\\\",\"; // {shortTableDesc}地址");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_Circuit\\\":\\\"\" + txtCircuit + \"\\\",\"; // {shortTableDesc}线路");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_ProvinceId\\\":\\\"\" + txtProvinceId + \"\\\",\"; // 所属省份，取自字典数据，统计用");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_RegionId\\\":\\\"\" + txtRegionId + \"\\\",\"; // 所属地区ID，取自字典数据");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_MapX\\\":\" + txtMapX + \",\"; // 地图坐标X");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_MapY\\\":\" + txtMapY + \",\"; // 地图坐标Y");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_QQMapUrl\\\":\\\"\" + txtQQMapUrl + \"\\\",\"; // 腾讯地图Url");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_AmapUrl\\\":\\\"\" + txtAmapUrl + \"\\\",\"; // 高德地图URL");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_BaiduMapUrl\\\":\\\"\" + txtBaiduMapUrl + \"\\\",\"; // 百度地图URL");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_ClassroomNum\\\":\" + txtClassroomNum + \",\"; // 教室数量");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_Introduce\\\":\\\"\" + txtIntroduce + \"\\\",\"; // {shortTableDesc}介绍");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_IntroduceUrl\\\":\\\"\" + txtIntroduceUrl + \"\\\",\"; // {shortTableDesc}介绍链接");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_Price\\\":\" + txtPrice + \",\"; // {shortTableDesc}租金费用");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_UseTime\\\":\\\"\" + txtUseTime + \"\\\",\"; // 启用时间");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_OutTime\\\":\\\"\" + txtOutTime + \"\\\",\"; // 停用时间");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_BeginTime\\\":\\\"\" + txtBeginTime + \"\\\",\"; // 营业时间");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_EndTime\\\":\\\"\" + txtEndTime + \"\\\",\"; // 截止时间");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_SortNumber\\\":\" + txtSortNumber + \",\"; // 排序编号");
                        //sb.AppendLine($"{tabTre}    strJson += \"\\\"F_Remark\\\":\\\"\" + txtRemark + \"\\\",\"; // {shortTableDesc}备注");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"State\\\":\" + txtState + \",\"; // 数据状态：0-正常；1-禁用；2-删");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_CreatorId\\\":\\\"\" + txtCreatorId + \"\\\",\"; // 创建人ID");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_CreateTime\\\":\\\"\" + txtCreateTime + \"\\\",\"; // 创建时间");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_ModifierId\\\":\\\"\" + txtModifierId + \"\\\",\"; // 编辑人ID");
                        //sb.AppendLine($"{tabTre}    //strJson += \"\\\"F_ModifiedTime\\\":\\\"\" + txtModifiedTime + \"\\\",\"; // 编辑时间");

                        sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    strJson = strJson.rTrim(\",\"); // 清除右边的逗号");
                        //sb.AppendLine($"{tabTre}    strJson += \"}}\";");
                        //sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    //console.info(\"保存提交前数据：\");");
                        sb.AppendLine($"{tabTre}    console.info(JSON.stringify(obj));");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    $.ajax({{");
                        sb.AppendLine($"{tabTre}        type: \"POST\",");
                        sb.AppendLine($"{tabTre}        url: \"/{areaName}/{controllerName}/Save/?rnd=\" + (Math.random() * 10),");
                        sb.AppendLine($"{tabTre}        data: JSON.stringify(obj),");
                        //sb.AppendLine($"{tabTre}        data: \"{{'json':'\" + encodeURIComponent(strJson) + \"'}}\",");
                        sb.AppendLine($"{tabTre}        contentType: \"application/json; charset=utf-8\",");
                        sb.AppendLine($"{tabTre}        dataType: \"json\",");
                        sb.AppendLine($"{tabTre}        success: function (rst) {{");
                        sb.AppendLine($"{tabTre}            Loading.Close();");
                        sb.AppendLine($"{tabTre}            console.info(rst);");
                        sb.AppendLine($"{tabTre}            if (rst && rst.success) {{");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}                refreshTable();");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}                $(\"#editModel\").modal(\"hide\");");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}                $(\"#btnSave\").prop(\"disabled\", \"\");");
                        sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                        sb.AppendLine($"{tabTre}            }} else {{");
                        sb.AppendLine($"{tabTre}                $.alert({{title: \"错误提示!\", content: rst.message }});");
                        sb.AppendLine($"{tabTre}            }}");
                        sb.AppendLine($"{tabTre}        }}");
                        sb.AppendLine($"{tabTre}    }});");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabOne}</script>");
                        sb.AppendLine($"");
                        sb.AppendLine($"}}");
                        sb.AppendLine($"");

                        File.WriteAllText(filePath, sb.ToString());
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"2）生成前端代码Html文件(Html)输出错误", ex);
                throw;
            }

            //MessageBox.Show($"代码已经生成在{path}下");
        }

        /// <summary>
        /// 开始创建生成表示层Table或者TreeView Html文件
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        private void CreateTreeListFile(string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            #region 命名空间检查

            //var websiteSpaceName = this.txtSpaceName.Text.Trim();

            //if (string.IsNullOrEmpty(websiteSpaceName))
            //{
            //    MessageBox.Show("控制器所在站点命名空间为空！");
            //    return;
            //}

            var rootSpaceName = this.txtSpaceName.Text.Trim();
            if (string.IsNullOrEmpty(rootSpaceName))
            {
                MessageBox.Show("根命名空间为空！");
                return;
            }

            var modelSpaceName = $"{rootSpaceName}.Model.Models"; // 实体文件命名空间
            var dtoSpaceName = $"{rootSpaceName}.Model.Dtos"; // 实体文件命名空间
            var areaRootSpaceName = $"{rootSpaceName}.Web.Areas"; // 区域根命名空间

            var enableLogging = RefMaterial?.EnableLogging;
            var enableCaching = RefMaterial?.EnableCaching;
            var efContext = RefMaterial?.EfContext;

            #endregion

            #region 检查区域根目录

            var areaRootPath = $"{selectPath}\\Areas\\"; // 区域根目录

            FileHelper.FilePathCheck(areaRootPath);

            #endregion

            try
            {
                #region 区域名称汇总

                Dictionary<string, string> areaList = AreaList(tableList);

                #endregion

                StringBuilder sb = new();

                foreach (KeyValuePair<string, string> keyValue in areaList)
                {
                    #region 检查区域及子目录

                    var title = keyValue.Value;
                    var areaName = title.ToUpperFirst(); // 区域名称

                    var areaPath = Path.Combine($"{areaRootPath}", $"{areaName}\\");
                    FileHelper.FilePathCheck(areaPath);

                    var viewsPath = Path.Combine($"{areaPath}", $"Views\\");
                    FileHelper.FilePathCheck(viewsPath);

                    var filePath = string.Empty;

                    #endregion

                    // 表列项数据
                    var tables = tableList.Where(entity => entity.Name.StartsWith(title)).ToList();

                    foreach (var table in tables)
                    {
                        var tableName = table.Name; // 表名
                        if (table.Comment == null) continue;
                        var tableDesc = table.Comment.Replace(":", "："); // 表描述
                        //var tableViewName = tableName.ToSingularModelName(); // 表实体名称
                        //if (isSingularEntity) tableViewName = tableViewName;
                        var tableModelName = tableName.ToSingularModelName(); // 表实体名称
                        var controllerName = GetControllerName(tableName);
                        if (!string.IsNullOrEmpty(controllerName) && !string.IsNullOrEmpty(areaName))
                            controllerName = controllerName.Replace(areaName, ""); // 控制器名去掉前面的去域名
                        var tableViewModelName = tableModelName + "ViewModel"; // 表ViewModel对象
                        var lowerTableName = tableModelName.ToLower(); // 小写表名
                        var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】
                        var pageName = "TableList";
                        filePath = $"{viewsPath}\\{controllerName}\\{pageName}.cshtml";
                        FileHelper.FilePathCheck(filePath);

                        if (baseTableDesc == tableName)
                        {
                            baseTableDesc = $"{{{baseTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                        }

                        var primaryKey = "Id"; // 主键
                        var primaryKeyType = "uniqueidentifier"; // Guid类型
                        var primaryKeyObjectName = primaryKey;
                        var primaryKeyObjectDesc = "";

                        //var dateInput = false; // 是否有日期输入字段

                        var tableColumn = columnList.Where(entity => entity.TableName == tableName).ToList();
                        var columnLength = tableColumn.Count;
                        var isTree = IsTree(tableColumn); // 是否树结构表
                        if (isTree)
                        {
                            pageName = "TreeList";
                            filePath = $"{viewsPath}\\{controllerName}\\{pageName}.cshtml";
                        }
                        sb = new StringBuilder();

                        sb.AppendLine($"@using {rootSpaceName}.Web.Models");
                        sb.AppendLine($"@using {rootSpaceName}.Common.Constants");
                        sb.AppendLine($"@model {tableViewModelName}");
                        sb.AppendLine($"");
                        sb.AppendLine($"@{{");
                        //sb.AppendLine($"{tabOne}ViewData[\"Title\"] = \"{baseTableDesc}\";");
                        sb.AppendLine($"{tabOne}Layout = \"~/Views/Shared/_Layout.cshtml\";");
                        sb.AppendLine($"}}");
                        sb.AppendLine($"");

                        if (isTree)
                        {
                            // 树结构数据页面

                            sb.AppendLine($"<div class=\"row-fluid\">");
                            sb.AppendLine($"{tabOne}@await Component.InvokeAsync(\"PageHeader\")");
                            sb.AppendLine($"</div>");
                            sb.AppendLine($"");
                            sb.AppendLine($"<div class=\"row\">");
                            sb.AppendLine($"    <div class=\"col-md-3\">");
                            sb.AppendLine($"        <section id=\"treeview\">");
                            sb.AppendLine($"            <div id=\"tree\"></div>");
                            sb.AppendLine($"        </section>");
                            sb.AppendLine($"    </div>");
                            sb.AppendLine($"");
                            sb.AppendLine($"    <div class=\"col-md-9\">");
                            sb.AppendLine($"{tabOne}<section class=\"table-responsive\">");
                            sb.AppendLine($"");
                            sb.AppendLine($"{tabTwo}<div id=\"toolbar\">");
                            sb.AppendLine($"{tabTre}<div class=\"form-inline\" role=\"form\">");
                            sb.AppendLine($"{tabTre}    <form class=\"form-inline form-toolbar\">");
                            sb.AppendLine($"{tabTre}    <input type=\"hidden\" id=\"ParentId\" />");
                            sb.AppendLine($"{tabTre}    <input type=\"hidden\" id=\"ParentName\" />");
                            sb.AppendLine($"{tabTre}        <div class=\"form-group\">");
                            sb.AppendLine($"{tabTre}            <input name=\"search\" class=\"form-control form-control-sm\" type=\"text\" placeholder=\"搜索\">");
                            if (columnLength > 10)
                            {
                                sb.AppendLine($"{tabTre}            <div class=\"input-group input-group-sm\">");
                                sb.AppendLine($"{tabTre}                <input id=\"startDate\" name=\"startDate\" class=\"form-control form-control-sm\" type=\"date\" style=\"margin-right: 0 !important;\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"开始日期\" />");
                                sb.AppendLine($"{tabTre}                <div class=\"input-group-prepend\">");
                                sb.AppendLine($"{tabTre}                    <div class=\"input-group-text form-control-sm\">至</div>");
                                sb.AppendLine($"{tabTre}                </div>");
                                sb.AppendLine($"{tabTre}                <input id=\"endDate\" name=\"endDate\" class=\"form-control form-control-sm\" type=\"date\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"结束日期\" />");
                                sb.AppendLine($"{tabTre}            </div>");
                            }
                            sb.AppendLine($"{tabTre}        </div>");
                            sb.AppendLine($"{tabTre}    </form>");

                            sb.AppendLine($"{tabTre}    <button id=\"remove\" class=\"btn btn-sm btn-danger\" disabled>");
                            sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-remove\"></i>批量删除");
                            sb.AppendLine($"{tabTre}    </button>");
                            sb.AppendLine($"{tabTre}    <button id=\"btnRoot\" class=\"btn btn-sm btn-primary\">");
                            sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-th-list\"></i>根菜单");
                            sb.AppendLine($"{tabTre}    </button>");
                            sb.AppendLine($"{tabTre}    <button id=\"btnAdd\" class=\"btn btn-sm btn-primary\">");
                            sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-plus\"></i>添加{baseTableDesc}");
                            sb.AppendLine($"{tabTre}    </button>");

                            //sb.AppendLine($"{tabTre}    <div class=\"btn-group\" role=\"group\" aria-label=\"query group\">");
                            //sb.AppendLine($"{tabTre}        <button id=\"btnSearch\" class=\"btn btn-sm btn-primary\" style=\"margin-right: 0!important;\">");
                            //sb.AppendLine($"{tabTre}            <i class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></i>查询");
                            //sb.AppendLine($"{tabTre}        </button>");
                            //sb.AppendLine($"{tabTre}        <button id=\"btnClear\" type=\"reset\" class=\"btn btn-secondary btn-sm\" title=\"清空查询条件\">");
                            //sb.AppendLine($"{tabTre}            <i class=\"glyphicon glyphicon-trash\" aria-hidden=\"true\"></i>");
                            //sb.AppendLine($"{tabTre}        </button>");
                            //sb.AppendLine($"{tabTre}    </div>");

                            sb.AppendLine($"{tabTre}    @await Html.PartialAsync(\"~/Views/Shared/Buttons/_ToolbarQueryGroup.cshtml\")");

                            //sb.AppendLine($"{tabTre}    <button id=\"btnRandomData\" class=\"btn btn-sm btn-primary\">");
                            //sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-list\"></i>填充数据");
                            //sb.AppendLine($"{tabTre}    </button>");

                            sb.AppendLine($"{tabTre}</div>");
                            sb.AppendLine($"{tabTwo}</div>");
                            sb.AppendLine($"");

                            sb.AppendLine($"{tabTwo}<table id=\"{lowerTableName}-table\" class=\"table table-striped table-sm table-hover\" data-buttons-prefix=\"btn-sm btn\" data-toolbar=\"#toolbar\"></table>");
                            sb.AppendLine($"{tabOne}</section>");

                            sb.AppendLine($"");
                            sb.AppendLine($"{tabOne}</div>");

                            sb.AppendLine($"");
                            sb.AppendLine($"</div>");

                        }
                        else
                        {
                            // 不含有树结构的页面
                            sb.AppendLine($"<div class=\"row-fluid\">");
                            sb.AppendLine($"");

                            sb.AppendLine($"{tabTwo}@await Component.InvokeAsync(\"PageHeader\")");
                            sb.AppendLine($"");

                            sb.AppendLine($"{tabTwo}<div id=\"toolbar\">");
                            sb.AppendLine($"{tabTre}<div class=\"form-inline\" role=\"form\">");
                            sb.AppendLine($"{tabTre}    <form class=\"form-inline form-toolbar\">");

                            sb.AppendLine($"{tabTre}        <div class=\"form-group\">");
                            sb.AppendLine($"{tabTre}            <input name=\"search\" class=\"form-control form-control-sm\" type=\"text\" placeholder=\"搜索\">");
                            if (columnLength > 10)
                            {
                                sb.AppendLine($"{tabTre}            <div class=\"input-group input-group-sm\">");
                                sb.AppendLine($"{tabTre}                <input id=\"startDate\" name=\"startDate\" class=\"form-control form-control-sm\" type=\"date\" style=\"margin-right: 0 !important;\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"开始日期\" />");
                                sb.AppendLine($"{tabTre}                <div class=\"input-group-prepend\">");
                                sb.AppendLine($"{tabTre}                    <div class=\"input-group-text form-control-sm\">至</div>");
                                sb.AppendLine($"{tabTre}                </div>");
                                sb.AppendLine($"{tabTre}                <input id=\"endDate\" name=\"endDate\" class=\"form-control form-control-sm\" type=\"date\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"结束日期\" />");
                                sb.AppendLine($"{tabTre}            </div>");
                            }
                            sb.AppendLine($"{tabTre}        </div>");
                            sb.AppendLine($"{tabTre}    </form>");

                            sb.AppendLine($"{tabTre}    <button id=\"remove\" class=\"btn btn-sm btn-danger\" disabled>");
                            sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-remove\"></i>批量删除");
                            sb.AppendLine($"{tabTre}    </button>");
                            sb.AppendLine($"{tabTre}    <button id=\"btnAdd\" class=\"btn btn-sm btn-primary\">");
                            sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-plus\"></i>添加{baseTableDesc}");
                            sb.AppendLine($"{tabTre}    </button>");

                            sb.AppendLine($"{tabTre}    @await Html.PartialAsync(\"~/Views/Shared/Buttons/_ToolbarQueryGroup.cshtml\")");

                            //sb.AppendLine($"{tabTre}    <button id=\"btnRandomData\" class=\"btn btn-sm btn-primary\">");
                            //sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-list\"></i>填充数据");
                            //sb.AppendLine($"{tabTre}    </button>");

                            sb.AppendLine($"{tabTre}</div>");
                            sb.AppendLine($"{tabTwo}</div>");
                            sb.AppendLine($"");
                            sb.AppendLine($"{tabOne}<div class=\"table-responsive\">");
                            sb.AppendLine($"{tabTwo}<table id=\"{lowerTableName}-table\" class=\"table table-striped table-sm table-hover\" data-buttons-prefix=\"btn-sm btn\" data-toolbar=\"#toolbar\"></table>");
                            sb.AppendLine($"{tabOne}</div>");

                            sb.AppendLine($"");
                            sb.AppendLine($"</div>");
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"<!-- {baseTableDesc}编辑模态窗体 //-->");

                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"<div class=\"modal fade\" id=\"editModel\" tabindex=\"-1\" role=\"dialog\" data-backdrop=\"static\" data-keyboard=\"false\" aria-labelledby=\"editModelLabel\" aria-hidden=\"true\">");
                        }
                        else
                        {
                            sb.AppendLine($"<div class=\"modal fade\" id=\"editModel\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\" aria-labelledby=\"editModelLabel\" aria-hidden=\"true\">");
                        }

                        sb.AppendLine($"{tabOne}<div class=\"modal-dialog modal-dialog-scrollable modal-dialog-centered\" role=\"document\">");
                        sb.AppendLine($"{tabTwo}<div class=\"modal-content\">");
                        sb.AppendLine($"{tabTre}<div class=\"modal-header\">");
                        sb.AppendLine($"{tabTre}    <h5 class=\"modal-title\" id=\"editModelLabel\">{baseTableDesc}编辑</h5>");
                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">");
                            sb.AppendLine($"{tabTre}        <span aria-hidden=\"true\">&times;</span>");
                            sb.AppendLine($"{tabTre}    </button>");
                        }
                        else
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button>");
                        }
                        sb.AppendLine($"{tabTre}</div>");
                        sb.AppendLine($"{tabTre}<div class=\"modal-body\">");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    <form class=\"form-horizontal\">");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述【列基本描述：枚举描述】
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            if (column.IsPK == 1)
                            {
                                primaryKey = columnName;
                                primaryKeyType = column.DataType;
                                primaryKeyObjectName = primaryKey;
                                primaryKeyObjectDesc = column.Comment;
                            }

                            var required = "";

                            if (column.IsPK == 0 && column.Nullable == 0 && column.DataType!.ToLower() != "int")
                            {
                                required = " required";
                            }

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            // 一些特殊的字段需要添加默认值
                            //var defaultValue = "";
                            //if (!string.IsNullOrEmpty(defaultValue))
                            //{
                            //    defaultValue = defaultValue.Replace("((", "").Replace("))", "");
                            //}
                            //if (column.DataType == "datetime" && !string.IsNullOrEmpty(defaultValue))
                            //{
                            //    defaultValue = DateTime.Now.ToString("yyyy-MM-dd");
                            //}
                            //if (column.DataType == "int")
                            //{
                            //    defaultValue = Guid.Empty.ToString();
                            //}

                            //if (column.Queryable == 1)
                            //{

                            if (NoHandlerColumn(column))
                            {
                                sb.AppendLine($"{tabTre}        <input type=\"hidden\" asp-for=\"{columnName}\" />");
                            }
                            else
                            {
                                //var datepicker = "";
                                //if (column.DataType == "datetime")
                                //{
                                //    dateInput = true; // 有日期输入字段
                                //    datepicker = " datepicker";
                                //}

                                var rightTwoLetter = columnName.Length > 2 ? columnName.Substring(columnName.Length - 2, 2).ToLower() : columnName.ToLower();

                                if (rightTwoLetter == "id" && columnName.ToLower() != "pid")
                                {
                                    sb.AppendLine($"{tabTre}        <input type=\"hidden\" asp-for=\"{columnName}\" />");
                                }
                                else
                                {
                                    if (columnName.ToLower() == "pid")
                                    {
                                        sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                        sb.AppendLine($"{tabTre}            <label asp-for=\"PName\" class=\"col-2 col-form-label col-form-label-sm\"></label>");
                                        sb.AppendLine($"{tabTre}            <div class=\"col-10 input-group\">");

                                        sb.AppendLine($"{tabTre}                <div class=\"input-group-prepend\">");
                                        sb.AppendLine($"{tabTre}                    <input type=\"text\" asp-for=\"Pid\" class=\"form-control form-control-sm\" readonly />");
                                        sb.AppendLine($"{tabTre}                </div>");
                                        sb.AppendLine($"{tabTre}                <input type=\"text\" class=\"form-control form-control-sm\" asp-for=\"PName\" placeholder=\"父级名称\" readonly>");
                                        sb.AppendLine($"{tabTre}                <div class=\"input-group-append\" onclick=\"javascript: ParentSelect();\">");
                                        sb.AppendLine($"{tabTre}                    <div class=\"input-group-text\" style=\"cursor:pointer;\" title=\"父级名称\">");
                                        sb.AppendLine($"{tabTre}                        <i class=\"fa fa-chevron-up\" aria-hidden=\"true\"></i>");
                                        sb.AppendLine($"{tabTre}                    </div>");
                                        sb.AppendLine($"{tabTre}                </div>");

                                        /*
                             <div class="input-group-prepend">
                                 <input type="text" asp-for="Pid" class="form-control form-control-sm" readonly />
                             </div>
                             <input type="text" class="form-control form-control-sm" asp-for="PName" placeholder="父级名称" readonly>
                             <div class="input-group-append" onclick="javascript: ParentSelect();">
                                 <div class="input-group-text" style="cursor:pointer;" title="父级名称">
                                     <i class="fa fa-chevron-up" aria-hidden="true"></i>
                                 </div>
                             </div>

                                         */

                                        sb.AppendLine($"{tabTre}            </div>");
                                        sb.AppendLine($"{tabTre}        </div>");
                                    }
                                    else
                                    {
                                        if (columnDesc.Contains("：") && (column.DataType!.Contains("int") || column.DataType!.Contains("int"))) // 有枚举描述，Razor
                                        {
                                            sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                            sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\"></label>");
                                            sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                            sb.AppendLine($"{tabTre}                <select asp-for=\"{columnName}\" class=\"form-control form-control-sm\" asp-items=\"Html.GetEnumSelectList<Enum{columnName}>()\"></select>");
                                            sb.AppendLine($"{tabTre}            </div>");
                                            sb.AppendLine($"{tabTre}        </div>");
                                        }
                                        else
                                        {
                                            if (column.DataType!.Contains("char") && (column.Length >= 255 || column.Length == -1) || column.DataType!.Contains("text"))
                                            {
                                                // 长文本字段varchar或nvarchar，长度大于等于255
                                                sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                                sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\"></label>");
                                                sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                                sb.AppendLine($"{tabTre}                <textarea asp-for=\"{columnName}\" class=\"form-control form-control-sm\"></textarea>");
                                                sb.AppendLine($"{tabTre}                <span asp-validation-for=\"{columnName}\" class=\"text-danger\"></span>");
                                                sb.AppendLine($"{tabTre}            </div>");
                                                sb.AppendLine($"{tabTre}        </div>");
                                            }
                                            else
                                            {
                                                //string objType = "type=\"text\" ";
                                                //if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                                                //{
                                                //    objType = "type=\"number\" ";
                                                //}

                                                sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                                sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\"></label>");
                                                sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                                sb.AppendLine($"{tabTre}                <input asp-for=\"{columnName}\" class=\"form-control form-control-sm\" />");
                                                sb.AppendLine($"{tabTre}                <span asp-validation-for=\"{columnName}\" class=\"text-danger\"></span>");
                                                sb.AppendLine($"{tabTre}            </div>");
                                                sb.AppendLine($"{tabTre}        </div>");
                                            }
                                        }
                                    }
                                }
                            }

                            if ((column.DataType!.Contains("char") && column.Length == -1)
                                || column.DataType!.Contains("text") || column.DataType!.Contains("blob"))
                            {
                                // 长文本字段text,ntext或varchar(max),nvarchar(max)
                                sb.AppendLine($"{tabTre}        <div class=\"form-group row\">");
                                sb.AppendLine($"{tabTre}            <label asp-for=\"{columnName}\" class=\"col-2 col-form-label col-form-label-sm{required}\"></label>");
                                sb.AppendLine($"{tabTre}            <div class=\"col-10\">");
                                sb.AppendLine($"{tabTre}                <textarea asp-for=\"{columnName}\" class=\"form-control form-control-sm\"></textarea>");
                                sb.AppendLine($"{tabTre}                <span asp-validation-for=\"{columnName}\" class=\"text-danger\"></span>");
                                sb.AppendLine($"{tabTre}            </div>");
                                sb.AppendLine($"{tabTre}        </div>");
                            }
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    </form>");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}</div>");
                        sb.AppendLine($"{tabTre}<div class=\"modal-footer\">");
                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn btn-sm btn-secondary\" data-dismiss=\"modal\">");
                        }
                        else
                        {
                            sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn btn-sm btn-secondary\" data-bs-dismiss=\"modal\">");
                        }
                        sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-floppy-remove\" aria-hidden=\"true\"></i>关闭");
                        sb.AppendLine($"{tabTre}    </button>");
                        sb.AppendLine($"{tabTre}    <button type=\"button\" class=\"btn btn-sm btn-primary\" id=\"btnSave\">");
                        sb.AppendLine($"{tabTre}        <i class=\"glyphicon glyphicon-floppy-saved\" aria-hidden=\"true\"></i>保存");
                        sb.AppendLine($"{tabTre}    </button>");
                        sb.AppendLine($"{tabTre}</div>");
                        sb.AppendLine($"{tabTwo}</div>");
                        sb.AppendLine($"{tabOne}</div>");
                        sb.AppendLine($"</div>");
                        sb.AppendLine($"");

                        if (isTree)
                        {
                            if (bootstrapVersion == 4)
                            {
                                sb.AppendLine($"<div class=\"modal fade\" id=\"ParentMenuModal\" tabindex=\"1\" role=\"dialog\" aria-hidden=\"true\" data-backdrop=\"static\" data-keyboard=\"false\">");
                            }
                            else
                            {
                                sb.AppendLine($"<div class=\"modal fade\" id=\"ParentMenuModal\" tabindex=\"1\" role=\"dialog\" aria-hidden=\"true\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\">");
                            }

                            sb.AppendLine($"    <div class=\"modal-dialog modal-dialog-centered\" role=\"document\">");
                            sb.AppendLine($"        <div class=\"modal-content\">");
                            sb.AppendLine($"            <div class=\"modal-header\">");
                            sb.AppendLine($"                <h5 class=\"modal-title\" id=\"myModalLabel\">父类名称选择</h5>");
                            sb.AppendLine($"                <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button>");
                            sb.AppendLine($"            </div>");
                            sb.AppendLine($"            <div style=\"padding:15px;\">");
                            sb.AppendLine($"                <div class=\"row\">");
                            sb.AppendLine($"                    <div class=\"container\">");
                            sb.AppendLine($"                        <section id=\"selecttreeview\">");
                            sb.AppendLine($"                            <div id=\"selecttree\"></div>");
                            sb.AppendLine($"                        </section>");
                            sb.AppendLine($"                    </div>");
                            sb.AppendLine($"                </div>");
                            sb.AppendLine($"            </div>");
                            sb.AppendLine($"            <div class=\"modal-footer\">");
                            sb.AppendLine($"                <button type=\"button\" class=\"btn btn-sm btn-secondary\" data-bs-dismiss=\"modal\">");
                            sb.AppendLine($"                    <i class=\"glyphicon glyphicon-floppy-remove\" aria-hidden=\"true\"></i>关闭");
                            sb.AppendLine($"                </button>");
                            sb.AppendLine($"                <button type=\"button\" class=\"btn btn-primary btn-sm\" id=\"btnUserSelect\">");
                            sb.AppendLine($"                    <i class=\"glyphicon glyphicon-floppy-saved\" aria-hidden=\"true\"></i>确定");
                            sb.AppendLine($"                </button>");
                            sb.AppendLine($"            </div>");
                            sb.AppendLine($"        </div><!-- /.modal-content -->");
                            sb.AppendLine($"    </div><!-- /.modal -->");
                            sb.AppendLine($"</div>");
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"@section Scripts {{");
                        sb.AppendLine($"{tabOne}@{{await Html.RenderPartialAsync(\"_ValidationScriptsPartial\");}}");

                        if (isTree)
                        {
                            sb.AppendLine($"    <link href=\"~/lib/bootstrap/tree/css/bstreeview.css\" rel=\"stylesheet\" />");
                            sb.AppendLine($"    <script src=\"~/lib/bootstrap/tree/js/bstreeview.js\"></script>");
                        }

                        var resourcePath = $"{areaName}/{controllerName}";

                        if (bootstrapVersion == 4)
                        {
                            sb.AppendLine($"{tabOne}    <environment names=\"Development\">");
                            sb.AppendLine($"{tabOne}        <link href=\"~/view-resources/{resourcePath}/TableList.css\" rel=\"stylesheet\" asp-append-version=\"true\" />");
                            sb.AppendLine($"{tabOne}        <script src=\"~/view-resources/{resourcePath}/{pageName}.js\" asp-append-version=\"true\"></script>");
                            sb.AppendLine($"{tabOne}    </environment>");
                            sb.AppendLine($"{tabOne}");
                            sb.AppendLine($"{tabOne}    <environment names=\"Staging,Production\">");
                            sb.AppendLine($"{tabOne}        <link href=\"~/view-resources/{resourcePath}/TableList.min.css\" rel=\"stylesheet\" asp-append-version=\"true\" />");
                            sb.AppendLine($"{tabOne}        <script src=\"~/view-resources/{resourcePath}/{pageName}.min.js\" asp-append-version=\"true\"></script>");
                            sb.AppendLine($"{tabOne}    </environment>");
                        }
                        else
                        {
                            sb.AppendLine($"{tabOne}    @if (@Environment.GetEnvironmentVariable(\"ASPNETCORE_ENVIRONMENT\") == \"Development\") {{");
                            sb.AppendLine($"{tabOne}        <link href=\"~/view-resources/{resourcePath}/TableList.css\" rel=\"stylesheet\" asp-append-version=\"true\" />");
                            sb.AppendLine($"{tabOne}        <script src=\"~/view-resources/{resourcePath}/{pageName}.js\" asp-append-version=\"true\"></script>");
                            sb.AppendLine($"{tabOne}    }} else {{");
                            sb.AppendLine($"{tabOne}        <link href=\"~/view-resources/{resourcePath}/TableList.min.css\" rel=\"stylesheet\" asp-append-version=\"true\" />");
                            sb.AppendLine($"{tabOne}        <script src=\"~/view-resources/{resourcePath}/{pageName}.min.js\" asp-append-version=\"true\"></script>");
                            sb.AppendLine($"{tabOne}    }}");

                        }

                        sb.AppendLine($"{tabOne}");
                        sb.AppendLine($"{tabOne}    <style type=\"text/css\">");
                        sb.AppendLine($"{tabOne}");
                        sb.AppendLine($"{tabOne}    </style>");
                        sb.AppendLine($"{tabOne}");
                        sb.AppendLine($"{tabOne}    <script type=\"text/javascript\">");
                        sb.AppendLine($"{tabOne}");
                        sb.AppendLine($"{tabOne}    </script>");
                        sb.AppendLine($"{tabOne}");
                        sb.AppendLine($"{tabOne}    }}");

                        #region MyRegion

                        //sb.AppendLine($"{tabOne}<link href=\"~/css/tablelist.css\" rel=\"stylesheet\" />");
                        //sb.AppendLine($"{tabOne}<link href=\"~/css/task.css\" rel=\"stylesheet\" />");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"    <style type=\"text/css\">");
                        //sb.AppendLine($"");
                        //if (isTree)
                        //{
                        //    sb.AppendLine($"        #tree {{");
                        //    sb.AppendLine($"            margin-top: 10px;");
                        //    sb.AppendLine($"        }}");
                        //    sb.AppendLine($"");
                        //}

                        //sb.AppendLine($"        td {{");
                        //sb.AppendLine($"            text-overflow: ellipsis;");
                        //sb.AppendLine($"            white-space: nowrap;");
                        //sb.AppendLine($"            overflow: hidden;");
                        //sb.AppendLine($"            word-break: keep-all;");
                        //sb.AppendLine($"        }}");

                        //sb.AppendLine($"        h2, .h2 {{");
                        //sb.AppendLine($"            font-size: 1.25rem;");
                        //sb.AppendLine($"        }}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"        table {{");
                        //sb.AppendLine($"            table-layout: fixed;");
                        //sb.AppendLine($"        }}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"	th, td {{");
                        //sb.AppendLine($"            word-wrap: break-word;");
                        //sb.AppendLine($"            word-break: break-all;");
                        //sb.AppendLine($"        }}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"        .fixed-table-container thead th .th-inner {{");
                        //sb.AppendLine($"            white-space: normal;");
                        //sb.AppendLine($"        }}");
                        //sb.AppendLine($"");


                        //sb.AppendLine($"    </style>");

                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabOne}<script type=\"text/javascript\">");
                        //sb.AppendLine($"{tabOne}");
                        //sb.AppendLine($"{tabTwo}var $table = $('#{lowerTableName}-table'),");
                        //sb.AppendLine($"{tabTre}$remove = $('#remove'),");
                        //sb.AppendLine($"{tabTre}selections = [],");
                        //sb.AppendLine($"{tabTre}key = '{primaryKey}';");
                        //sb.AppendLine($"{tabTwo}");

                        //var defaultPrimaryKeyValue = "0";
                        //if (primaryKeyType == "int")
                        //{
                        //    sb.AppendLine($"{tabTwo}var defaultGuid = '00000000-0000-0000-0000-000000000000';");
                        //}

                        //if (primaryKeyType == "int")
                        //{
                        //    defaultPrimaryKeyValue = "0";
                        //}

                        ////sb.AppendLine($"{tabTwo}var circleModalId = \"circleModal\", $circleModal = null; // 圆形进度条窗体及对象");
                        ////sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}var pageNumber = 1, pageSize = 10;"); // , width = 0
                        //sb.AppendLine($"{tabTwo}var pageListUrl = \"/{areaName}/{controllerName}/PageList\";");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}$(function () {{");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$table = $('#{lowerTableName}-table'),");
                        //sb.AppendLine($"{tabTre}    $remove = $('#remove');");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$(\"#btnAdd\").on(function () {{");
                        ////sb.AppendLine($"{tabTre}");
                        ////sb.AppendLine($"{tabTre}    // 默认Guid类型字段初始化处理");

                        //foreach (var column in tableColumn)
                        //{
                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment; // 列描述

                        //    if (column.IsPK == 1 && column.DataType == "int")
                        //    {
                        //        sb.AppendLine($"{tabTre}    $(\"#{columnName}\").val(\"0\"); // {columnDesc}");
                        //    }
                        //}

                        ////sb.AppendLine($"{tabTre}    $(\"#Name\").focus();");

                        //sb.AppendLine($"{tabTre}    $(\"#editModelLabel\").html(\"{baseTableDesc}信息添加\");");
                        //sb.AppendLine($"{tabTre}    $('#editModel').modal('toggle');");
                        //sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}initTable();");
                        ////sb.AppendLine($"");
                        ////sb.AppendLine($"{tabTre}$table.find(\"thead\").addClass(\"thead-dark\");");
                        //sb.AppendLine($"");
                        //if (isTree)
                        //{
                        //    sb.AppendLine($"{tabTre}getTreeView();");
                        //}
                        //sb.AppendLine($"{tabTre}// 关键词查询");
                        //sb.AppendLine($"{tabTre}$('input[name=\"search\"]').off('keydown').on('keydown', function (e) {{");
                        //sb.AppendLine($"{tabTre}    if (e.code == \"Enter\") {{");
                        //sb.AppendLine($"{tabTre}        pageNumber = 1;");
                        //sb.AppendLine($"{tabTre}        refreshTable();");
                        //sb.AppendLine($"{tabTre}    }}");
                        //sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"{tabTre}");

                        //sb.AppendLine($"            // 搜索");
                        //sb.AppendLine($"            $(\"#btnSearch\").off('click').on('click', function () {{");
                        //sb.AppendLine($"                pageNumber = 1;");
                        //sb.AppendLine($"                refreshTable();");
                        //sb.AppendLine($"            }});");
                        //sb.AppendLine($"");

                        ////if (dateInput)
                        ////{
                        ////    sb.AppendLine($"{tabTre}$(\".datepicker\").datetimepicker({{");
                        ////    sb.AppendLine($"{tabTre}    language: \"zh-CN\",");
                        ////    sb.AppendLine($"{tabTre}    autoclose: true,//选中之后自动隐藏日期选择框");
                        ////    sb.AppendLine($"{tabTre}    clearBtn: true,//清除按钮");
                        ////    sb.AppendLine($"{tabTre}    //todayBtn: true,//今日按钮");
                        ////    sb.AppendLine($"{tabTre}    minView: \"month\", //选择日期后，不会再跳转去选择时分秒");
                        ////    sb.AppendLine($"{tabTre}    format: \"yyyy-mm-dd\"//日期格式");
                        ////    sb.AppendLine($"{tabTre}}});");
                        ////}

                        //sb.AppendLine($"{tabTre}");
                        ////sb.AppendLine($"{tabTre}// 填充随机数据");
                        ////sb.AppendLine($"{tabTre}$(\"#btnRandomData\").off('click').on('click', function () {{");
                        ////sb.AppendLine($"{tabTre}    CTD.Modal.CircleMessage(circleModalId, \"数据填充操作正在进行中，请稍候...\");");
                        ////sb.AppendLine($"{tabTre}    $(\"#\" + circleModalId).modal(\"toggle\");");
                        ////sb.AppendLine($"{tabTre}    $.ajax({{");
                        ////sb.AppendLine($"{tabTre}        url: '/{areaName}/{controllerName}/SqlBulkRandomData/?rnd=' + (Math.random() * 10),");
                        ////sb.AppendLine($"{tabTre}        type: 'GET',");
                        ////sb.AppendLine($"{tabTre}        data: {{ rnd: (Math.random() * 16) }},");
                        ////sb.AppendLine($"{tabTre}        success: function (rst) {{");
                        ////sb.AppendLine($"{tabTre}            $(\"#\" + circleModalId).modal(\"hide\");");
                        ////sb.AppendLine($"{tabTre}            if (rst && rst.success) {{");
                        ////sb.AppendLine($"{tabTre}                refreshTable();");
                        ////sb.AppendLine($"{tabTre}                $.alert({{ title: '操作成功!', content: rst.message }});");
                        ////sb.AppendLine($"{tabTre}            }} else {{");
                        ////sb.AppendLine($"{tabTre}                modals.error(rst.message ?? rst.Message);");
                        ////sb.AppendLine($"{tabTre}            }}");
                        ////sb.AppendLine($"{tabTre}        }}");
                        ////sb.AppendLine($"{tabTre}    }});");
                        ////sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"{tabTwo}}});");
                        //sb.AppendLine($"{tabTwo}");

                        //if (isTree)
                        //{
                        //    sb.AppendLine($"        function getTreeView() {{");
                        //    sb.AppendLine($"            var url = \"/{areaName}/{controllerName}/TreeData/?id=&selectId=\";");
                        //    sb.AppendLine($"            $.get(url + \"&rnd=\" + (Math.random() * 10), function (rst) {{");
                        //    sb.AppendLine($"                //console.log(rst);");
                        //    sb.AppendLine($"                console.log(rst.Data);");
                        //    sb.AppendLine($"                if (rst && rst.success) {{");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"                    $('#tree').bstreeview({{");
                        //    sb.AppendLine($"                        data: rst.Data,");
                        //    sb.AppendLine($"                        expandIcon: 'fa fa-angle-down fa-fw',");
                        //    sb.AppendLine($"                        collapseIcon: 'fa fa-angle-right fa-fw',");
                        //    sb.AppendLine($"                        indent: 1.25,");
                        //    sb.AppendLine($"                        parentsMarginLeft: '1.25rem',");
                        //    sb.AppendLine($"                        openNodeLinkOnNewTab: true");
                        //    sb.AppendLine($"                    }});");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"                    $(\".list-group-item\").on('click', function (e) {{");
                        //    sb.AppendLine($"                        var id = e.target.getAttribute('id');");
                        //    sb.AppendLine($"                        var text = $(e.target).text()");
                        //    sb.AppendLine($"                        if (id.length > 0) {{");
                        //    sb.AppendLine($"                            $(\"#Pid\").val(id);");
                        //    sb.AppendLine($"                            $(\"#ParentId\").val(id);");
                        //    sb.AppendLine($"                            $(\"#ParentName\").val(text);");
                        //    sb.AppendLine($"                            pageNumber = 1;");
                        //    sb.AppendLine($"                            refreshTable();");
                        //    sb.AppendLine($"                        }}");
                        //    sb.AppendLine($"                    }});");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"                }} else {{");
                        //    sb.AppendLine($"                    modals.error(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"                }}");
                        //    sb.AppendLine($"            }});");
                        //    sb.AppendLine($"        }}");
                        //}

                        //sb.AppendLine($"{tabTwo}// 刷新表格数据");
                        //sb.AppendLine($"{tabTwo}function refreshTable() {{");
                        //sb.AppendLine($"{tabTre}$table.bootstrapTable({{ url: pageListUrl }});");
                        //sb.AppendLine($"{tabTre}$table.bootstrapTable('refresh', {{ pageNumber: pageNumber, pageSize: pageSize }});");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// 初始化表");
                        //sb.AppendLine($"{tabTwo}function initTable() {{");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}//先销毁表格");
                        //sb.AppendLine($"{tabTre}$table.bootstrapTable('destroy');");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$table.bootstrapTable({{");
                        //sb.AppendLine($"{tabTre}    height: getHeight(),");
                        //sb.AppendLine($"{tabTre}    method: 'get', // 请求方式（*）");
                        //sb.AppendLine($"{tabTre}    dataType: \"json\", // 数据类型");
                        //sb.AppendLine($"{tabTre}    url: pageListUrl, // 请求后台地址,");
                        //sb.AppendLine($"{tabTre}    toolbar: '#toolbar', //工具按钮用哪个容器");
                        //sb.AppendLine($"{tabTre}    theadClasses: 'thead-dark', // 表头样式");
                        //sb.AppendLine($"{tabTre}    striped: true, // 使表格带有条纹");
                        //sb.AppendLine($"{tabTre}    uniqueId: key, // 唯一标识");
                        //sb.AppendLine($"{tabTre}    idField: key, // 标识哪个字段为id主键");
                        //sb.AppendLine($"{tabTre}    pagination: true, // 在表格底部显示分页工具栏");
                        //sb.AppendLine($"{tabTre}    pageSize: pageSize, // 分页大小");
                        //sb.AppendLine($"{tabTre}    pageNumber: pageNumber, // 当前页码");
                        //sb.AppendLine($"{tabTre}    pageList: [10, 20, 50, 100, 200, 500],");
                        //sb.AppendLine($"{tabTre}    sidePagination: \"server\", //表格分页的位置");
                        //sb.AppendLine($"{tabTre}    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder");
                        //sb.AppendLine($"{tabTre}    //设置为limit可以获取limit, offset, search, sort, order");
                        //sb.AppendLine($"{tabTre}    queryParamsType: \"undefined\",");
                        //sb.AppendLine($"{tabTre}    queryParams: function queryParams(params) {{ //设置查询参数");
                        //sb.AppendLine($"{tabTre}        var param = {{");
                        //sb.AppendLine($"{tabTre}            pageNumber: params.pageNumber,");
                        //sb.AppendLine($"{tabTre}            pageSize: params.pageSize,");

                        //if (isTree)
                        //{
                        //    sb.AppendLine($"{tabTre}            id: $(\"#Pid\").val(),");
                        //}

                        //sb.AppendLine($"{tabTre}            title: $(\"input[name='search']\").val()");
                        //sb.AppendLine($"{tabTre}        }};");
                        //sb.AppendLine($"{tabTre}        pageNumber = params.pageNumber;");
                        //sb.AppendLine($"{tabTre}        return param;");
                        //sb.AppendLine($"{tabTre}    }},");
                        //sb.AppendLine($"{tabTre}    columns: [");
                        //sb.AppendLine($"{tabTre}        [");
                        //sb.AppendLine($"{tabTre}            {{");
                        //sb.AppendLine($"{tabTre}                field: 'checked',");
                        //sb.AppendLine($"{tabTre}                checkbox: true");
                        //sb.AppendLine($"{tabTre}            }}, {{");
                        //sb.AppendLine($"{tabTre}                title: '序号',");
                        //sb.AppendLine($"{tabTre}                field: 'RowNumber',");
                        //sb.AppendLine($"{tabTre}                width: 60,");
                        //sb.AppendLine($"{tabTre}                align: 'center',");
                        //sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                        //sb.AppendLine($"{tabTre}                	var options = $table.bootstrapTable('getOptions');");
                        //sb.AppendLine($"{tabTre}                	return options.pageSize * (options.pageNumber - 1) + index + 1;");
                        //sb.AppendLine($"{tabTre}                }}");
                        //sb.AppendLine($"{tabTre}            }}, {{");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                        //    var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】                   

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    if (NoHandlerColumn(column))
                        //    {
                        //        // 去除字段
                        //    }
                        //    else
                        //    {
                        //        var rightTwoLetter = columnName.Length > 2 ? columnName.Substring(columnName.Length - 2, 2).ToLower() : columnName.ToLower();

                        //        if (rightTwoLetter == "id")
                        //        {
                        //            // 尾部2个字符为ID的不显示
                        //        }
                        //        else
                        //        {
                        //            sb.AppendLine($"{tabTre}                field: '{columnName}',");
                        //            sb.AppendLine($"{tabTre}                title: '{baseColumnDesc}',");

                        //            var tdWidth = 60; // 普通列宽带
                        //            if (column.DataType == "datetime")
                        //            {
                        //                tdWidth = 105; // 日期列宽带
                        //            }
                        //            else
                        //            {
                        //                if (column.Length > 0)
                        //                {
                        //                    tdWidth = 120;
                        //                }
                        //            }

                        //            sb.AppendLine($"{tabTre}                width: {tdWidth},");
                        //            sb.AppendLine($"{tabTre}                halign: 'center',");

                        //            var align = "center";
                        //            if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                        //            {
                        //                align = "right"; // 数值型
                        //            }
                        //            else if (column.Length > 0)
                        //            {
                        //                align = "left"; // 字符型
                        //            }

                        //            sb.AppendLine($"{tabTre}                align: '{align}',");

                        //            var formatter = "";
                        //            if (column.Length > 0)
                        //            {
                        //                formatter = "tipsFormatter"; // 字符型
                        //            }

                        //            if (column.DataType == "datetime") // 日期时间列表格式
                        //            {
                        //                sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                        //                sb.AppendLine($"{tabTre}                    return (value == null || value.length == 0) ? \"\" : value.toDateTimeString();");
                        //                sb.AppendLine($"{tabTre}                }}");
                        //            }
                        //            else if (column.DataType == "date") // 日期列表格式
                        //            {
                        //                sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                        //                sb.AppendLine($"{tabTre}                    return (value == null || value.length == 0) ? \"\" : value.toDateString();");
                        //                sb.AppendLine($"{tabTre}                }}");
                        //            }
                        //            else
                        //            {
                        //                if (!string.IsNullOrEmpty(formatter))
                        //                {
                        //                    sb.AppendLine($"{tabTre}                formatter: {formatter}");
                        //                }
                        //            }

                        //            sb.AppendLine($"{tabTre}            }}, {{");
                        //        }
                        //    }
                        //}

                        //foreach (var column in tableColumn.Where(s => s.Name == "State"))
                        //{
                        //    sb.AppendLine($"{tabTre}                field: 'State',");
                        //    sb.AppendLine($"{tabTre}                title: '状态',");
                        //    sb.AppendLine($"{tabTre}                width: 60,");
                        //    sb.AppendLine($"{tabTre}                halign: 'center',");
                        //    sb.AppendLine($"{tabTre}                align: 'center',");
                        //    sb.AppendLine($"{tabTre}                formatter: stateFormatter");
                        //    sb.AppendLine($"{tabTre}            }}, {{");
                        //}

                        //sb.AppendLine($"{tabTre}                title: '操作',");
                        //sb.AppendLine($"{tabTre}                width: 90,");
                        //sb.AppendLine($"{tabTre}                halign: 'center',");
                        //sb.AppendLine($"{tabTre}                align: 'center',");
                        //sb.AppendLine($"{tabTre}                events: operateEvents,");
                        //sb.AppendLine($"{tabTre}                formatter: operateFormatter");
                        //sb.AppendLine($"{tabTre}            }}");
                        //sb.AppendLine($"{tabTre}        ]");
                        //sb.AppendLine($"{tabTre}    ],");
                        //sb.AppendLine($"{tabTre}    formatLoadingMessage: function () {{");
                        //sb.AppendLine($"{tabTre}        return \"请稍等，正在加载中...\";");
                        //sb.AppendLine($"{tabTre}    }},");
                        //sb.AppendLine($"{tabTre}    formatNoMatches: function () {{ //没有匹配的结果");
                        //sb.AppendLine($"{tabTre}        return '无符合条件的记录';");
                        //sb.AppendLine($"{tabTre}    }}");
                        //sb.AppendLine($"{tabTre}}});");
                        ////sb.AppendLine($"{tabTre}");
                        ////sb.AppendLine($"{tabTre}// sometimes footer render error.");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$table.find(\"thead\").addClass(\"thead-dark\");");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}setTimeout(function () {{");
                        //sb.AppendLine($"{tabTre}    $table.bootstrapTable('resetView');");
                        //sb.AppendLine($"{tabTre}    $('[data-toggle=\"tooltip\"]').tooltip();");
                        //sb.AppendLine($"{tabTre}}}, 200);");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$table.on('check.bs.table uncheck.bs.table ' +");
                        //sb.AppendLine($"{tabTre}    'check-all.bs.table uncheck-all.bs.table', function () {{");
                        //sb.AppendLine($"{tabTre}        $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}        // save your data, here just save the current page");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}        selections = getIdSelections();");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}        // push or splice the selections if you want to save all data selections");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}    }});");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$remove.off('click').on('click', function () {{ // 批量删除");
                        //sb.AppendLine($"{tabTre}    var ids = getIdSelections();");

                        //if (isLogicalDelete)
                        //{
                        //    sb.AppendLine($"{tabTre}    $remove.prop('disabled', true);");
                        //    sb.AppendLine($"{tabTre}    BatchLogicalDelete(ids); // 批量逻辑删除");
                        //}
                        //else
                        //{
                        //    //sb.AppendLine($"{tabTre}    $table.bootstrapTable('remove', {{");
                        //    //sb.AppendLine($"{tabTre}        field: key,");
                        //    //sb.AppendLine($"{tabTre}        values: ids");
                        //    //sb.AppendLine($"{tabTre}    }});");
                        //    sb.AppendLine($"{tabTre}    $remove.prop('disabled', true);");
                        //    sb.AppendLine($"{tabTre}    BatchDelete(ids.toString()); // 批量删除");
                        //}

                        //sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$(window).resize(function () {{");
                        //sb.AppendLine($"{tabTre}    $table.bootstrapTable('resetView', {{");
                        //sb.AppendLine($"{tabTre}        height: getHeight()");
                        //sb.AppendLine($"{tabTre}    }});");
                        //sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTwo}// 获取选择项");
                        //sb.AppendLine($"{tabTwo}function getIdSelections() {{");
                        //sb.AppendLine($"{tabTre}return $.map($table.bootstrapTable('getSelections'), function (row) {{");
                        //sb.AppendLine($"{tabTre}    return row[key];");
                        //sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTwo}// 操作内容格式化");
                        //sb.AppendLine($"{tabTwo}function operateFormatter(value, row, index) {{");
                        ////sb.AppendLine($"{tabTre}return [");
                        ////sb.AppendLine($"{tabTre}    '<a class=\"edit\" href=\"javascript:void(0)\" title=\"修改{shortTableDesc}\">',");
                        ////sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-edit\"></i>',");
                        ////sb.AppendLine($"{tabTre}    '</a>  ',");
                        ////sb.AppendLine($"{tabTre}    '<a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{shortTableDesc}\">',");
                        ////sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                        ////sb.AppendLine($"{tabTre}    '</a>'");
                        ////sb.AppendLine($"{tabTre}].join('');");
                        //sb.AppendLine($"{tabTre}var edit = ['<a class=\"edit\" href=\"javascript:void(0)\" title=\"修改{baseTableDesc}\">',");
                        //sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-edit\"></i>',");
                        //sb.AppendLine($"{tabTre}    '</a>'];");
                        //sb.AppendLine($"{tabTre}");

                        //if (isLogicalDelete)
                        //{
                        //    sb.AppendLine($"{tabTre}var enable = ['  <a class=\"enable\" href=\"javascript:void(0)\" title=\"启用{baseTableDesc}\">',");
                        //    sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-ok\"></i>',");
                        //    sb.AppendLine($"{tabTre}    '</a>'];");
                        //    sb.AppendLine($"{tabTre}");
                        //    sb.AppendLine($"{tabTre}var disable = ['  <a class=\"disable\" href=\"javascript:void(0)\" title=\"禁用{baseTableDesc}\">',");
                        //    sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-ban-circle\"></i>',");
                        //    sb.AppendLine($"{tabTre}    '</a>'];");
                        //    sb.AppendLine($"{tabTre}");
                        //    sb.AppendLine($"{tabTre}var remove = ['  <a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{baseTableDesc}\">',");
                        //    sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                        //    sb.AppendLine($"{tabTre}    '</a>'];");
                        //    sb.AppendLine($"{tabTre}");
                        //    sb.AppendLine($"{tabTre}// 数据状态：0-正常；1-禁用；2-删除");
                        //    sb.AppendLine($"{tabTre}if (row.State == 0) {{");
                        //    sb.AppendLine($"{tabTre}    edit = edit.concat(disable);");
                        //    sb.AppendLine($"{tabTre}    edit = edit.concat(remove);");
                        //    sb.AppendLine($"{tabTre}}}");
                        //    sb.AppendLine($"{tabTre}if (row.State == 1) {{");
                        //    sb.AppendLine($"{tabTre}    edit = edit.concat(enable);");
                        //    sb.AppendLine($"{tabTre}    edit = edit.concat(remove);");
                        //    sb.AppendLine($"{tabTre}}}");
                        //    sb.AppendLine($"{tabTre}if (row.State == 2) {{");
                        //    sb.AppendLine($"{tabTre}    edit = edit.concat(enable);");
                        //    sb.AppendLine($"{tabTre}    edit = edit.concat(disable);");
                        //    sb.AppendLine($"{tabTre}}}");
                        //    sb.AppendLine($"{tabTre}");
                        //}
                        //else
                        //{
                        //    sb.AppendLine($"{tabTre}var remove = ['  <a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{baseTableDesc}\">',");
                        //    sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                        //    sb.AppendLine($"{tabTre}    '</a>'];");
                        //    sb.AppendLine($"{tabTre}edit = edit.concat(remove);");
                        //}

                        //sb.AppendLine($"{tabTre}return edit.join('');");

                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// 操作事件响应");
                        //sb.AppendLine($"{tabTwo}window.operateEvents = {{");
                        //sb.AppendLine($"{tabTre}'click .edit': function (e, value, row, index) {{");
                        //sb.AppendLine($"{tabTre}    //alert('You click edit action, row: ' + JSON.stringify(row));");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}    //debugger;");
                        //sb.AppendLine($"{tabTre}    //console.info(\"编辑前获取行数据：\");");
                        //sb.AppendLine($"{tabTre}    console.info(row);");
                        //sb.AppendLine($"{tabTre}");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                        //    var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】                  

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    //if (column.Queryable == 1)
                        //    //{
                        //    //if (column.Name.IndexOf("State") > -1
                        //    //    //|| column.Name.IndexOf("CreatorId") > -1
                        //    //    //|| column.Name.IndexOf("CreateTime") > -1
                        //    //    //|| column.Name.IndexOf("LastModifierId") > -1
                        //    //    //|| column.Name.IndexOf("LastModifyTime") > -1
                        //    //    //|| column.Name.IndexOf("ModifierId") > -1
                        //    //    //|| column.Name.IndexOf("ModifiedTime") > -1
                        //    //    )
                        //    //{
                        //    //    sb.AppendLine($"{tabTre}    //$(\"#{columnName}\").val(row.{columnName}); // {columnDesc}");
                        //    //}
                        //    //else
                        //    //{}                    
                        //    //}
                        //    //else
                        //    //{
                        //    //    sb.AppendLine($"{tabTre}    //$(\"#{columnName}\").val(row.{columnName}); // {columnDesc}");
                        //    //}

                        //    //if (column.DataType == "datetime")
                        //    //{
                        //    //    dateInput = true; // 有日期输入字段
                        //    //}

                        //    sb.AppendLine($"{tabTre}    $(\"#{columnName}\").val(row.{columnName}); // {columnDesc}");

                        //}

                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}    $(\"#editModelLabel\").html(\"{baseTableDesc}信息修改\");");
                        //sb.AppendLine($"{tabTre}    $('#editModel').modal('toggle');");
                        //sb.AppendLine($"{tabTre}}},");

                        //if (isLogicalDelete)
                        //{
                        //    sb.AppendLine($"{tabTre}'click .enable': function (e, value, row, index) {{");
                        //    sb.AppendLine($"{tabTre}	Enable(row[key]); // 启用行数据");
                        //    sb.AppendLine($"{tabTre}}}, 'click .disable': function (e, value, row, index) {{");
                        //    sb.AppendLine($"{tabTre}	Disable(row[key]); // 禁用行数据");
                        //}
                        //sb.AppendLine($"{tabTre}'click .remove': function (e, value, row, index) {{");

                        //if (isLogicalDelete)
                        //{
                        //    sb.AppendLine($"{tabTre}    LogicalDelete(row[key]); // 逻辑删除行数据");
                        //}
                        //else
                        //{
                        //    //sb.AppendLine($"{tabTre}$table.bootstrapTable('remove', {{");
                        //    //sb.AppendLine($"{tabTre}	field: key,");
                        //    //sb.AppendLine($"{tabTre}	values: [row[key]]");
                        //    //sb.AppendLine($"{tabTre}}});");
                        //    sb.AppendLine($"{tabTre}Delete(row[key]); // 删除行数据");
                        //}

                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTwo}}};");

                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// 获取内容高度");
                        //sb.AppendLine($"{tabTwo}function getHeight() {{");
                        //sb.AppendLine($"{tabTre}var heightCorrection = 35;");
                        //sb.AppendLine($"{tabTre}return $(window).height() - $('h2').outerHeight(true) - heightCorrection;");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"");

                        //if (isLogicalDelete)
                        //{
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 启用数据");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"function Enable(id) {{");
                        //    sb.AppendLine($"	if (confirm(\"您确定要启用该{baseTableDesc}吗？\")) {{");
                        //    sb.AppendLine($"		$.ajax({{");
                        //    sb.AppendLine($"			type: \"POST\",");
                        //    sb.AppendLine($"			url: \"/{areaName}/{controllerName}/Enable/\" + id + \"?rnd=\" + (Math.random() * 10),");
                        //    //sb.AppendLine($"			data: \"{{'id':''}}\",");
                        //    sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                        //    sb.AppendLine($"			dataType: \"json\",");
                        //    sb.AppendLine($"			success: function (rst) {{");
                        //    sb.AppendLine($"				//console.info(rst);");
                        //    sb.AppendLine($"				if (rst && rst.success) {{");
                        //    sb.AppendLine($"					refreshTable();");
                        //    sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}} else {{");
                        //    sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}}");
                        //    sb.AppendLine($"			}}");
                        //    sb.AppendLine($"		}});");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 禁用数据");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"function Disable(id) {{");
                        //    sb.AppendLine($"	if (confirm(\"您确定要禁用该{baseTableDesc}吗？\")) {{");
                        //    sb.AppendLine($"		$.ajax({{");
                        //    sb.AppendLine($"			type: \"POST\",");
                        //    sb.AppendLine($"			url: \"/{areaName}/{controllerName}/Disable/\" + id + \"?rnd=\" + (Math.random() * 10),");
                        //    //sb.AppendLine($"			data: \"{{'id':''}}\",");
                        //    sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                        //    sb.AppendLine($"			dataType: \"json\",");
                        //    sb.AppendLine($"			success: function (rst) {{");
                        //    sb.AppendLine($"				//console.info(rst);");
                        //    sb.AppendLine($"				if (rst && rst.success) {{");
                        //    sb.AppendLine($"					refreshTable();");
                        //    sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}} else {{");
                        //    sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}}");
                        //    sb.AppendLine($"			}}");
                        //    sb.AppendLine($"		}});");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 逻辑删除");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"function LogicalDelete(id) {{");
                        //    sb.AppendLine($"	if (confirm(\"您确定要逻辑删除该{baseTableDesc}吗？\")) {{");
                        //    sb.AppendLine($"		$.ajax({{");
                        //    sb.AppendLine($"			type: \"POST\",");
                        //    sb.AppendLine($"			url: \"/{areaName}/{controllerName}/LogicalDelete/\" + id + \"?rnd=\" + (Math.random() * 10),");
                        //    //sb.AppendLine($"			data: \"{{'id':''}}\",");
                        //    sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                        //    sb.AppendLine($"			dataType: \"json\",");
                        //    sb.AppendLine($"			success: function (rst) {{");
                        //    sb.AppendLine($"				//console.info(rst);");
                        //    sb.AppendLine($"				if (rst && rst.success) {{");
                        //    sb.AppendLine($"					refreshTable();");
                        //    sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}} else {{");
                        //    sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}}");
                        //    sb.AppendLine($"			}}");
                        //    sb.AppendLine($"		}});");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 批量逻辑删除");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"function BatchLogicalDelete(ids) {{");
                        //    sb.AppendLine($"	if (confirm(\"您确定要批量逻辑删除这些{baseTableDesc}吗？\")) {{");
                        //    sb.AppendLine($"		$.ajax({{");
                        //    sb.AppendLine($"			type: \"POST\",");
                        //    sb.AppendLine($"			url: \"/{areaName}/{controllerName}/BatchLogicalDelete/\" + ids + \"?rnd=\" + (Math.random() * 10),");
                        //    //sb.AppendLine($"			data: \"{{'ids':''}}\",");
                        //    sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                        //    sb.AppendLine($"			dataType: \"json\",");
                        //    sb.AppendLine($"			success: function (rst) {{");
                        //    sb.AppendLine($"				//console.info(rst);");
                        //    sb.AppendLine($"				if (rst && rst.success) {{");
                        //    sb.AppendLine($"					refreshTable();");
                        //    sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}} else {{");
                        //    sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}}");
                        //    sb.AppendLine($"			}}");
                        //    sb.AppendLine($"		}});");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //}
                        //else
                        //{
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 物理删除数据");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"function Delete(id) {{");
                        //    sb.AppendLine($"	if (confirm(\"您确定要删除该{baseTableDesc}吗？\")) {{");
                        //    sb.AppendLine($"		$.ajax({{");
                        //    sb.AppendLine($"			type: \"POST\",");
                        //    sb.AppendLine($"			url: \"/{areaName}/{controllerName}/Delete/\" + id + \"?rnd=\" + (Math.random() * 10),");
                        //    //sb.AppendLine($"			data: \"{{'id':'\" + id + \"'}}\",");
                        //    sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                        //    sb.AppendLine($"			dataType: \"json\",");
                        //    sb.AppendLine($"			success: function (rst) {{");
                        //    sb.AppendLine($"				//console.info(rst);");
                        //    sb.AppendLine($"				if (rst && rst.success) {{");
                        //    sb.AppendLine($"					refreshTable();");
                        //    sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}} else {{");
                        //    sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}}");
                        //    sb.AppendLine($"			}}");
                        //    sb.AppendLine($"		}});");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 批量物理删除");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"function BatchDelete(ids) {{");
                        //    sb.AppendLine($"	if (confirm(\"您确定要批量删除这些{baseTableDesc}吗？\")) {{");
                        //    sb.AppendLine($"		$.ajax({{");
                        //    sb.AppendLine($"			type: \"POST\",");
                        //    sb.AppendLine($"			url: \"/{areaName}/{controllerName}/BatchDelete/\" + ids + \"?rnd=\" + (Math.random() * 10),");
                        //    //sb.AppendLine($"			data: \"{{'ids':'\" + ids + \"'}}\",");
                        //    sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                        //    sb.AppendLine($"			dataType: \"json\",");
                        //    sb.AppendLine($"			success: function (rst) {{");
                        //    sb.AppendLine($"				//console.info(rst);");
                        //    sb.AppendLine($"				if (rst && rst.success) {{");
                        //    sb.AppendLine($"					refreshTable();");
                        //    sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}} else {{");
                        //    sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                        //    sb.AppendLine($"				}}");
                        //    sb.AppendLine($"			}}");
                        //    sb.AppendLine($"		}});");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //}

                        //sb.AppendLine($"{tabTwo}$(function () {{");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}$('#editModel').on('hidden.bs.modal', function () {{ // 关闭模态窗体事件");
                        //sb.AppendLine($"{tabTre}    $(\"#editModel form\")[0].reset();");
                        //sb.AppendLine($"{tabTre}    $(\"#btnSave\").prop(\"disabled\", false); // 解除保存按钮禁用");
                        //sb.AppendLine($"{tabTre}    $(\"#editModel form input[type='hidden']\").val(\"\");");
                        //sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}$(\"#btnSave\").unbind(\"click\").bind(\"click\", function () {{ // {baseTableDesc}数据保存");
                        //sb.AppendLine($"");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述                 

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    sb.AppendLine($"{tabTre}    var txt{columnName} = $(\"#{columnName}\").val(); // {columnDesc}");

                        //}

                        //sb.AppendLine($"");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                        //    var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    if (NoHandlerColumn(column))
                        //    {
                        //        // 不处理
                        //    }
                        //    else
                        //    {
                        //        // 必填项
                        //        if (columnName == "Name" || column.Nullable == 0)
                        //        {
                        //            // https://codeseven.github.io/toastr/
                        //            sb.AppendLine($"{tabTre}    if ( txt{columnName} == undefined || txt{columnName}.length == 0) {{");
                        //            sb.AppendLine($"{tabTre}        toastr.error('请填写{baseColumnDesc}名称！');");
                        //            sb.AppendLine($"{tabTre}        $(\"#{columnName}\").focus();");
                        //            sb.AppendLine($"{tabTre}        return;");
                        //            sb.AppendLine($"{tabTre}    }}");
                        //        }
                        //    }
                        //}

                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    $(\"#btnSave\").prop(\"disabled\", \"disabled\");");
                        //sb.AppendLine($"");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述                    

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    //if (NoHandlerColumn(column))
                        //    //{
                        //    //    // 不处理
                        //    //}
                        //    //else{}

                        //    // 数值项
                        //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                        //    {
                        //        sb.AppendLine($"{tabTre}    if (txt{columnName} == undefined || txt{columnName}.length == 0) {{");
                        //        sb.AppendLine($"{tabTre}        txt{columnName} = \"0\";");
                        //        sb.AppendLine($"{tabTre}    }}");
                        //    }
                        //}

                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    // 字符串输入超长处理");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                        //    var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】
                        //    if (columnDesc != baseColumnDesc) continue; // 列描述中有冒号的不提示，一般是下拉数据

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    if (column.DataType!.ToLower().Contains("char") && column.Length > 0 && column.Length < 50)
                        //    {
                        //        sb.AppendLine($"{tabTre}    if (txt{columnName} && txt{columnName}.length > {column.Length}) {{");
                        //        sb.AppendLine($"{tabTre}        toastr.error('{baseColumnDesc}超过设定长度{column.Length}！');");
                        //        sb.AppendLine($"{tabTre}        $(\"#{columnName}\").focus();");
                        //        sb.AppendLine($"{tabTre}        return;");
                        //        sb.AppendLine($"{tabTre}    }}");
                        //    }
                        //}

                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    // 字符串中异常字符处理");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                        //    var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    // 文本字段检查异常字符
                        //    if (column.DataType!.Contains("char") || column.DataType!.Contains("text"))
                        //    {
                        //        // /'%7C%5C%5C%7C%5C/%7C%5C%22%7C%5C%7C%7C%3E%7C%3C%7C%5C*%7C%5C?%7C:/g
                        //        var matchString = "%2F'%7C%5C%5C%7C%5C%22%7C%5C%7C%7C%3E%7C%3C%7C%5C*%7C%5C%3F%2Fg";
                        //        matchString = HttpUtility.UrlDecode(matchString);
                        //        sb.AppendLine($"{tabTre}    if (txt{columnName} != undefined && txt{columnName}.length > 0) {{");
                        //        sb.AppendLine($"{tabTre}        txt{columnName} = txt{columnName}.replace({matchString}, \"\"); // {columnDesc}");
                        //        sb.AppendLine($"{tabTre}    }}");
                        //    }
                        //}

                        //sb.AppendLine($"");
                        ////sb.AppendLine($"{tabTre}    var strJson = \"{{\";");
                        //sb.AppendLine($"{tabTre}    var obj = {{}};");
                        ////sb.AppendLine($"");

                        //foreach (var column in tableColumn)
                        //{
                        //    // 默认日期类型自动不参与增改
                        //    if (column.DataType == "timestamp") continue;

                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                        //    var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                        //    #region Column特性

                        //    var customColumnName = GetColumnName(columnName);
                        //    if (columnName != customColumnName)
                        //    {
                        //        columnName = customColumnName;
                        //    }

                        //    #endregion

                        //    //if (NoHandlerColumn(column))
                        //    //{
                        //    //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                        //    //    {
                        //    //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\" + txt{columnName} + \",\"; // {columnDesc}");
                        //    //    }
                        //    //    else
                        //    //    {
                        //    //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\\\"\" + txt{columnName} + \"\\\",\"; // {columnDesc}");
                        //    //    }
                        //    //}
                        //    //else
                        //    //{
                        //    //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                        //    //    {
                        //    //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\" + txt{columnName} + \",\"; // {columnDesc}");
                        //    //    }
                        //    //    else
                        //    //    {
                        //    //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\\\"\" + txt{columnName} + \"\\\",\"; // {columnDesc}");
                        //    //    }
                        //    //}

                        //    sb.AppendLine($"{tabTre}    obj.{columnName} = txt{columnName}; // {columnDesc}");
                        //}

                        //sb.AppendLine($"");
                        ////sb.AppendLine($"{tabTre}    strJson = strJson.rTrim(\",\"); // 清除右边的逗号");
                        ////sb.AppendLine($"{tabTre}    strJson += \"}}\";");
                        ////sb.AppendLine($"");
                        ////sb.AppendLine($"{tabTre}    //console.info(\"保存提交前数据：\");");
                        ////sb.AppendLine($"{tabTre}    //console.info(strJson);");
                        //sb.AppendLine($"{tabTre}    //console.info(JSON.stringify(obj));");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    $.ajax({{");
                        //sb.AppendLine($"{tabTre}        type: \"POST\",");
                        //sb.AppendLine($"{tabTre}        url: \"/{areaName}/{controllerName}/Save/?rnd=\" + (Math.random() * 10),");
                        //sb.AppendLine($"{tabTre}        data: JSON.stringify(obj),");
                        ////sb.AppendLine($"{tabTre}        data: \"{{'json':'\" + encodeURIComponent(strJson) + \"'}}\",");
                        //sb.AppendLine($"{tabTre}        contentType: \"application/json; charset=utf-8\",");
                        //sb.AppendLine($"{tabTre}        dataType: \"json\",");
                        //sb.AppendLine($"{tabTre}        success: function (rst) {{");
                        //sb.AppendLine($"{tabTre}            //console.info(rst);");
                        //sb.AppendLine($"{tabTre}            if (rst && rst.success) {{");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}                refreshTable();");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}                $(\"#editModel\").modal(\"hide\");");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}                $(\"#btnSave\").prop(\"disabled\", \"\");");
                        //sb.AppendLine($"{tabTre}            }} else {{");
                        //sb.AppendLine($"{tabTre}                $.alert({{title: \"错误提示!\", content: rst.message }});");
                        //sb.AppendLine($"{tabTre}            }}");
                        //sb.AppendLine($"{tabTre}        }}");
                        //sb.AppendLine($"{tabTre}    }});");
                        //sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTwo}}});");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabOne}</script>");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"}}");
                        //sb.AppendLine($"");

                        #endregion

                        File.WriteAllText(filePath, sb.ToString());
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"2）生成前端代码Html文件(Tree)输出错误", ex);
                throw;
            }
        }

        /// <summary>
        /// 区域名称汇总
        /// </summary>
        /// <param name="tableList">表列表</param>
        /// <returns></returns>
        private static Dictionary<string, string> AreaList(List<Tables> tableList)
        {
            Dictionary<string, string> areaList = new Dictionary<string, string>();

            foreach (var table in tableList)
            {
                var s = table.Name.Split('_')[0];

                if (!areaList.ContainsKey(s))
                {
                    areaList.Add(s, s);
                }
            }

            return areaList;
        }

        #endregion

        #region 3）生成区域控制器及视图文件

        /// <summary>
        /// 生成区域控制器及视图文件
        /// </summary>
        /// <param name="dbName">数据库名称</param>  
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        private void CreateControllerFile(string dbName, string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            try
            {
                #region 命名空间检查

                //var websiteSpaceName = this.txtSpaceName.Text.Trim();

                //if (string.IsNullOrEmpty(websiteSpaceName))
                //{
                //    MessageBox.Show("控制器所在站点命名空间为空！");
                //    return;
                //}

                var rootSpaceName = this.txtSpaceName.Text.Trim();
                if (string.IsNullOrEmpty(rootSpaceName))
                {
                    MessageBox.Show("根命名空间为空！");
                    return;
                }

                var modelSpaceName = $"{rootSpaceName}.Model.Models"; // 实体文件命名空间
                var dtoSpaceName = $"{rootSpaceName}.Model.Dtos"; // 实体文件命名空间
                var areaRootSpaceName = $"{rootSpaceName}.Web.Areas"; // 区域根命名空间

                var enableLogging = RefMaterial?.EnableLogging ?? false;
                var enableCaching = RefMaterial?.EnableCaching ?? false;
                var efContext = RefMaterial?.EfContext;
                var strCachingIOC = enableCaching ? "IDistributedCache distributedCache, " : "";
                var strBaseCachingIOC = enableCaching ? "distributedCache, " : "";

                #endregion

                #region 检查区域根目录

                var areaRootPath = $"{selectPath}\\Areas\\"; // 区域根目录

                FileHelper.FilePathCheck(areaRootPath);

                #endregion

                StringBuilder sb = new();
                StringBuilder referencesBase = new();
                StringBuilder referencesExt = new();

                // 数据库类型
                DBType dbType = (DBType)Enum.Parse(typeof(DBType), DbConfig?.DBType!);

                #region 引用文件

                referencesBase.AppendLine($"using System;");
                referencesBase.AppendLine($"using System.Collections;");
                referencesBase.AppendLine($"using System.Collections.Generic;");
                referencesBase.AppendLine($"using System.Linq;");
                referencesBase.AppendLine($"using System.Threading.Tasks;");
                referencesBase.AppendLine($"using AutoMapper;");
                referencesBase.AppendLine($"using Microsoft.AspNetCore.Mvc;");
                referencesBase.AppendLine($"using Microsoft.AspNetCore.Mvc.Rendering;");
                referencesBase.AppendLine($"using Microsoft.EntityFrameworkCore;");
                if (enableCaching)
                {
                    referencesBase.AppendLine($"using Microsoft.Extensions.Caching.Distributed;");
                }
                if (enableLogging)
                {
                    referencesBase.AppendLine($"using Microsoft.Extensions.Logging;");
                }
                referencesBase.AppendLine($"using {rootSpaceName}.Common.Constants;");
                referencesBase.AppendLine($"using {rootSpaceName}.Common.Utility;");
                referencesBase.AppendLine($"using {rootSpaceName}.Model;");
                referencesBase.AppendLine($"using {rootSpaceName}.Model.Data;");
                referencesBase.AppendLine($"using {rootSpaceName}.Model.Dtos;");
                referencesBase.AppendLine($"using {rootSpaceName}.Model.Models;");
                referencesBase.AppendLine($"using {rootSpaceName}.Model.Extensions;");
                referencesBase.AppendLine($"using {rootSpaceName}.Web.Utility;");
                referencesBase.AppendLine($"using System.Web;");

                referencesExt.AppendLine($"using {rootSpaceName}.Web.Models;");

                if (!string.IsNullOrEmpty(efContext))
                {
                    referencesExt.AppendLine($"using {rootSpaceName}.IService;");
                }

                #endregion

                #region 区域名称汇总

                Dictionary<string, string> areaList = new();

                foreach (var table in tableList)
                {
                    var s = table.Name.Split('_')[0];

                    if (!string.IsNullOrEmpty(s) && !areaList.ContainsKey(s))
                    {
                        areaList.Add(s, s);
                    }
                }

                #endregion

                foreach (KeyValuePair<string, string> keyValue in areaList)
                {
                    sb = new StringBuilder();

                    #region 检查区域及子目录

                    var title = keyValue.Value;
                    var areaName = title.ToUpperFirst(); // 区域名称
                    var controllerSpaceName = $"{areaRootSpaceName}.{areaName}.Controllers"; // 控制器命名空间

                    var areaPath = Path.Combine($"{areaRootPath}", $"{areaName}\\");
                    FileHelper.FilePathCheck(areaPath);

                    var controllerPath = Path.Combine($"{areaPath}", $"Controllers\\");
                    FileHelper.FilePathCheck(controllerPath);

                    var dataPath = Path.Combine($"{areaPath}", $"Data\\");
                    FileHelper.FilePathCheck(dataPath);

                    var modelsPath = Path.Combine($"{areaPath}", $"Models\\");
                    FileHelper.FilePathCheck(modelsPath);

                    var viewsPath = Path.Combine($"{areaPath}", $"Views\\");
                    FileHelper.FilePathCheck(viewsPath);

                    #endregion

                    #region 区域基类控制器文件

                    // 区域基类控制器，需要在Web程序Utility目录下添加基类控制器BaseController
                    var baseControllerfilePath = Path.Combine($"{controllerPath}", $"AreaBaseController.cs");

                    sb.Append(referencesBase);
                    //sb.AppendLine($"using {rootSpaceName}.Web.Utility;");
                    sb.AppendLine($"");
                    sb.AppendLine($"namespace {controllerSpaceName}");
                    sb.AppendLine($"{{");
                    //sb.AppendLine($"{tabOne}[Area(\"{areaName}\")]");
                    //sb.AppendLine($"{tabOne}[Route(\"{areaName}/{{controller}}/{{action = Index}}/{{id?}}\")]");
                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {{areaName}}区域基类控制器");
                    sb.AppendLine($"{tabOne}/// </summary>");
                    sb.AppendLine($"{tabOne}public class AreaBaseController : BaseController");
                    sb.AppendLine($"{tabOne}{{");
                    sb.AppendLine($"{tabTwo}#region 构造函数及方法注入");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}private readonly IMapper _mapper;");
                    if (enableCaching)
                    {
                        sb.AppendLine($"{tabTwo}private readonly IDistributedCache _distributedCache;");
                    }
                    if (enableLogging)
                    {
                        sb.AppendLine($"{tabTwo}private readonly ILogger<AreaBaseController> _logger;");
                    }
                    sb.AppendLine($"{tabTwo}private readonly {efContext} _context;");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}/// <summary>");
                    sb.AppendLine($"{tabTwo}/// {{areaName}}区域基类控制器构造函数");
                    sb.AppendLine($"{tabTwo}/// </summary>");
                    sb.AppendLine($"{tabTwo}public AreaBaseController(ILogger<AreaBaseController> logger, {strCachingIOC}{efContext} context, IMapper mapper) : base(logger, context, {strBaseCachingIOC}mapper)");
                    sb.AppendLine($"{tabTwo}{{");
                    sb.AppendLine($"{tabTre}this._mapper = mapper;");
                    if (enableLogging)
                    {
                        sb.AppendLine($"{tabTre}this._logger = logger;");
                    }

                    sb.AppendLine($"{tabTre}this._context = context;");
                    if (enableCaching)
                    {
                        sb.AppendLine($"{tabTre}this._distributedCache = distributedCache;");
                    }
                    sb.AppendLine($"{tabTwo}}}");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}#endregion");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine($"}}");

                    File.WriteAllText(baseControllerfilePath, sb.ToString());

                    #endregion

                    // 表列项数据
                    var tables = tableList.Where(entity => entity.Name.StartsWith(title)).ToList();

                    foreach (var table in tables)
                    {
                        var tableName = table.Name; // 表名
                        if (table.Comment == null) continue;
                        var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                        var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】
                        //var tableViewName = tableName.ToSingularModelName(); // 表实体名称
                        //if (isSingularEntity) tableViewName = tableViewName;
                        var tableModelName = tableName.ToSingularModelName(); // 表实体名称
                        var tableDbSetName = tableName.ToPluralizeModelName(); // 表数据集名称
                        var tableDtoName = tableModelName + "Dto"; // 表Dto对象
                        var tableViewModelName = tableModelName + "ViewModel"; // 表ViewModel对象
                        var instanceModelName = GetInstanceModelName(tableName); // 表实体实例化名称
                        var controllerName = GetControllerName(tableName) ?? "";
                        var alternativeName = GetAlternativeName(tableName); // 表主题首字母(表代称)
                        if (!string.IsNullOrEmpty(controllerName) && !string.IsNullOrEmpty(areaName))
                            controllerName = controllerName.Replace(areaName, ""); // 控制器名去掉前面的去域名

                        if (baseTableDesc == tableName)
                        {
                            baseTableDesc = $"{{{baseTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                        }

                        var controllerFilePath = Path.Combine($"{controllerPath}", $"{controllerName}Controller.cs");
                        var viewModelFilePath = Path.Combine($"{modelsPath}", $"{tableViewModelName}.cs"); // 视图数据对象

                        var tableColumns = columnList.Where(entity => entity.TableName == tableName).ToList();
                        var columnLength = tableColumns.Count;

                        var isTree = IsTree(tableColumns); // 是否是树结构对象
                        var hasDisabled = HasDisabled(tableColumns); // 是否有Disabled列

                        #region 列名称集合

                        var columns = string.Empty;
                        var keyName = string.Empty;
                        var keyDataType = string.Empty;
                        var hasCreateTime = false;
                        var hasUpdateTime = false;
                        foreach (var column in tableColumns)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name;
                            if (!string.IsNullOrEmpty(columnName))
                            {
                                if (columnName.ToLower() == "createtime") hasCreateTime = true;
                                if (columnName.ToLower() == "modifiedtime") hasUpdateTime = true;
                            }
                            if (columnName?.Length < 4)
                            {
                                var customColumnName = columnName.ToUpperFirst();
                                if (columnName != customColumnName)
                                {
                                    columnName = customColumnName;
                                }
                            }
                            columns += columnName + ",";

                            if (column.IsPK == 1)
                            {
                                keyName = column.Name;
                                keyDataType = column.DataType;
                            }
                        }
                        columns = columns.TrimEnd(',');

                        #endregion

                        #region 控制器输出

                        sb = new StringBuilder();

                        // 引用文件
                        sb.Append(referencesBase);
                        sb.Append(referencesExt);
                        sb.AppendLine($"");
                        sb.AppendLine($"namespace {controllerSpaceName}");
                        sb.AppendLine($"{{");
                        sb.AppendLine($"{tabOne}/// <summary>");
                        sb.AppendLine($"{tabOne}/// {baseTableDesc}控制器");
                        sb.AppendLine($"{tabOne}/// </summary>");
                        sb.AppendLine($"{tabOne}[Area(\"{areaName}\")]");
                        sb.AppendLine($"{tabOne}public class {controllerName}Controller : AreaBaseController");
                        sb.AppendLine($"{tabOne}{{");
                        sb.AppendLine($"{tabTwo}#region 控制器初始化");
                        sb.AppendLine($"{tabTwo}");

                        //if (enableLogging){}if (!string.IsNullOrEmpty(efContext)){}
                        sb.AppendLine($"{tabTwo}private readonly IMapper _mapper;");
                        if (enableCaching)
                        {
                            sb.AppendLine($"{tabTwo}private readonly IDistributedCache _distributedCache;");
                        }
                        if (enableLogging)
                        {
                            sb.AppendLine($"{tabTwo}private readonly ILogger<{controllerName}Controller> _logger;");
                        }
                        sb.AppendLine($"{tabTwo}private readonly {efContext} _context;");
                        //sb.AppendLine($"{tabTwo}private readonly IBaseService _iBaseService;");

                        #region 注入方法

                        var ioc = string.Empty;
                        ioc += $"ILogger<{controllerName}Controller> logger, {strCachingIOC}";
                        ioc += $"{efContext} context, ";
                        ioc += $"IMapper mapper, ";
                        //ioc += $"IBaseService baseService";
                        ioc = ioc.Trim().TrimEnd(',');

                        #endregion

                        sb.AppendLine($"{tabTwo}");
                        sb.AppendLine($"{tabTwo}/// <summary>");
                        sb.AppendLine($"{tabTwo}/// {baseTableDesc}控制器构造函数");
                        sb.AppendLine($"{tabTwo}/// </summary>");
                        sb.AppendLine($"{tabTwo}public {controllerName}Controller({ioc}) : base(logger, {strBaseCachingIOC}context, mapper)");
                        sb.AppendLine($"{tabTwo}{{");
                        sb.AppendLine($"{tabTre}this._logger = logger;");
                        sb.AppendLine($"{tabTre}this._mapper = mapper;");
                        sb.AppendLine($"{tabTre}this._context = context;");
                        //sb.AppendLine($"{tabTre}this._iBaseService = baseService;");
                        if (enableCaching)
                        {
                            sb.AppendLine($"{tabTre}this._distributedCache = distributedCache;");
                        }
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"{tabTwo}");
                        sb.AppendLine($"{tabTwo}#endregion");
                        sb.AppendLine($"{tabTwo}");
                        sb.AppendLine($"{tabTwo}// GET: {areaName}/{controllerName}");
                        sb.AppendLine($"{tabTwo}public async Task<IActionResult> Index()");
                        sb.AppendLine($"{tabTwo}{{");
                        sb.AppendLine($"{tabTre}return _context.{tableDbSetName} != null ? \r\n                          View(await _context.{tableDbSetName}.Skip(0).Take(50).ToListAsync()) :\r\n                          Problem(\"Entity set '{dbName}Context.{tableDbSetName}' is null.\");");
                        //sb.AppendLine($"{tabTre}return View(await _context.{tableDbSetName}.ToListAsync());");
                        sb.AppendLine($"{tabTwo}}}");

                        #region MyRegion

                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// GET: {areaName}/{controllerName}/Details/5");
                        //sb.AppendLine($"{tabTwo}public async Task<IActionResult> Details(int? id)");
                        //sb.AppendLine($"{tabTwo}{{");
                        //sb.AppendLine($"{tabTre}if (id == null)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    return NotFound();");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}var {instanceModelName} = await _context.{tableViewName}");
                        //sb.AppendLine($"{tabTre}    .FirstOrDefaultAsync(m => m.Id == id);");
                        //sb.AppendLine($"{tabTre}if ({instanceModelName} == null)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    return NotFound();");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}return View({instanceModelName});");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// GET: {areaName}/{controllerName}/Create");
                        //sb.AppendLine($"{tabTwo}public IActionResult Create()");
                        //sb.AppendLine($"{tabTwo}{{");
                        //sb.AppendLine($"{tabTre}return View();");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// POST: {areaName}/{controllerName}/Create");
                        //sb.AppendLine($"{tabTwo}// To protect from overposting attacks, enable the specific properties you want to bind to, for ");
                        //sb.AppendLine($"{tabTwo}// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.");
                        //sb.AppendLine($"{tabTwo}[HttpPost]");
                        //sb.AppendLine($"{tabTwo}[ValidateAntiForgeryToken]");
                        //sb.AppendLine($"{tabTwo}public async Task<IActionResult> Create([FromBody] {tableViewName} {instanceModelName})");
                        //sb.AppendLine($"{tabTwo}{{");
                        ////sb.AppendLine($"{tabTre}if (ModelState.IsValid)");
                        ////sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    _context.Add({instanceModelName});");
                        //sb.AppendLine($"{tabTre}    await _context.SaveChangesAsync();");
                        //sb.AppendLine($"{tabTre}    return RedirectToAction(nameof(Index));");
                        ////sb.AppendLine($"{tabTre}}}");
                        ////sb.AppendLine($"{tabTre}return View({instanceModelName});");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// GET: {areaName}/{controllerName}/Edit/5");
                        //sb.AppendLine($"{tabTwo}public async Task<IActionResult> Edit(int? id)");
                        //sb.AppendLine($"{tabTwo}{{");
                        //sb.AppendLine($"{tabTre}if (id == null)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    return NotFound();");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTre}var {instanceModelName} = await _context.{tableViewName}.FindAsync(id);");
                        //sb.AppendLine($"{tabTre}if ({instanceModelName} == null)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    return NotFound();");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTre}return View({instanceModelName});");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// POST: {areaName}/{controllerName}/Edit/5");
                        //sb.AppendLine($"{tabTwo}// To protect from overposting attacks, enable the specific properties you want to bind to, for ");
                        //sb.AppendLine($"{tabTwo}// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.");
                        //sb.AppendLine($"{tabTwo}[HttpPost]");
                        //sb.AppendLine($"{tabTwo}[ValidateAntiForgeryToken]");
                        //sb.AppendLine($"{tabTwo}public async Task<IActionResult> Edit(int id, [FromBody] {tableViewName} {instanceModelName})");
                        //sb.AppendLine($"{tabTwo}{{");
                        //sb.AppendLine($"{tabTre}if (id != {instanceModelName}.Id)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    return NotFound();");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTre}");
                        ////sb.AppendLine($"{tabTre}if (ModelState.IsValid)");
                        ////sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    try");
                        //sb.AppendLine($"{tabTre}    {{");
                        //sb.AppendLine($"{tabTre}        _context.Update({instanceModelName});");
                        //sb.AppendLine($"{tabTre}        await _context.SaveChangesAsync();");
                        //sb.AppendLine($"{tabTre}    }}");
                        //sb.AppendLine($"{tabTre}    catch (DbUpdateConcurrencyException)");
                        //sb.AppendLine($"{tabTre}    {{");
                        //sb.AppendLine($"{tabTre}        if (!{tableViewName}Exists({instanceModelName}.Id))");
                        //sb.AppendLine($"{tabTre}        {{");
                        //sb.AppendLine($"{tabTre}            return NotFound();");
                        //sb.AppendLine($"{tabTre}        }}");
                        //sb.AppendLine($"{tabTre}        else");
                        //sb.AppendLine($"{tabTre}        {{");
                        //sb.AppendLine($"{tabTre}            throw;");
                        //sb.AppendLine($"{tabTre}        }}");
                        //sb.AppendLine($"{tabTre}    }}");
                        //sb.AppendLine($"{tabTre}    return RedirectToAction(nameof(Index));");
                        ////sb.AppendLine($"{tabTre}}}");
                        ////sb.AppendLine($"{tabTre}return View({instanceModelName});");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"{tabTwo}");
                        //sb.AppendLine($"{tabTwo}// GET: {areaName}/{controllerName}/Delete/5");
                        //sb.AppendLine($"{tabTwo}public async Task<IActionResult> Delete(int? id)");
                        //sb.AppendLine($"{tabTwo}{{");
                        //sb.AppendLine($"{tabTre}if (id == null)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    return NotFound();");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}var {instanceModelName} = await _context.{tableViewName}");
                        //sb.AppendLine($"{tabTre}    .FirstOrDefaultAsync(m => m.Id == id);");
                        //sb.AppendLine($"{tabTre}if ({instanceModelName} == null)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    return NotFound();");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}return View({instanceModelName});");
                        //sb.AppendLine($"{tabTwo}}}");

                        #endregion

                        sb.AppendLine($"{tabTwo}");
                        sb.AppendLine($"{tabTwo}// POST: {areaName}/{controllerName}/Delete/5");
                        sb.AppendLine($"{tabTwo}[HttpPost, ActionName(\"Delete\")]");
                        //sb.AppendLine($"{tabTwo}[ValidateAntiForgeryToken]");
                        sb.AppendLine($"{tabTwo}public async Task<IActionResult> DeleteConfirmed(int id)");
                        sb.AppendLine($"{tabTwo}{{");
                        sb.AppendLine($"            var method = $\"{{RouteData.Values[\"controller\"]}}.{{RouteData.Values[\"action\"]}}\";");
                        sb.AppendLine($"{tabTre}using var transaction = await _context.Database.BeginTransactionAsync();");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}try");
                        sb.AppendLine($"{tabTre}{{");

                        sb.AppendLine($"{tabTre}if (_context.{tableDbSetName} == null)");
                        sb.AppendLine($"{tabTre}{{");
                        sb.AppendLine($"{tabTre}    return Problem(\"Entity set '{dbName}Context.{tableDbSetName}' is null.\");");
                        sb.AppendLine($"{tabTre}}}");
                        sb.AppendLine($"{tabTre}var {instanceModelName} = await _context.{tableDbSetName}.FindAsync(id);");
                        sb.AppendLine($"{tabTre}if ({instanceModelName} != null)");
                        sb.AppendLine($"{tabTre}{{");
                        sb.AppendLine($"{tabTre}    _context.{tableDbSetName}.Remove({instanceModelName});");
                        sb.AppendLine($"{tabTre}}}");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}await _context.SaveChangesAsync();");
                        sb.AppendLine($"{tabTre}await transaction.CommitAsync(); // 事务提交");
                        sb.AppendLine($"{tabTre}return Json(new {{ success = true, message = \"{baseTableDesc}删除成功\" }});");

                        //sb.AppendLine($"{tabTre}    if (_context.{tableDbSetName} == null)\r\n            {{\r\n                return Problem(\"Entity set '{dbName}Context.{tableDbSetName}' is null.\");\r\n            }}");
                        //sb.AppendLine($"{tabTre}    if ({tableViewName}Exists(id))");
                        //sb.AppendLine($"{tabTre}    {{");
                        //sb.AppendLine($"{tabTre}        var {instanceModelName} = await _context.{tableDbSetName}.FindAsync(id);");
                        //sb.AppendLine($"{tabTre}        _context.{tableDbSetName}.Remove({instanceModelName});");
                        //sb.AppendLine($"{tabTre}        await _context.SaveChangesAsync();");
                        //sb.AppendLine($"{tabTre}        await transaction.CommitAsync(); // 事务提交");
                        //sb.AppendLine($"{tabTre}        return Json(new {{ success = true, message = \"{baseTableDesc}删除成功\" }});");
                        //sb.AppendLine($"{tabTre}    }}");
                        //sb.AppendLine($"{tabTre}    else");
                        //sb.AppendLine($"{tabTre}    {{");
                        //sb.AppendLine($"{tabTre}        return NotFound();");
                        //sb.AppendLine($"{tabTre}    }}");

                        sb.AppendLine($"{tabTre}}}");
                        sb.AppendLine($"{tabTre}catch (Exception ex)");
                        sb.AppendLine($"{tabTre}{{");
                        sb.AppendLine($"{tabTre}    await transaction.RollbackAsync(); // 事务回滚");
                        sb.AppendLine($"{tabTre}    _logger.LogError($\"{{method}}：{{ex}}\");");
                        sb.AppendLine($"{tabTre}    return Json(new {{ success = false, message = ex.Message }});");
                        sb.AppendLine($"{tabTre}}}");

                        //sb.AppendLine($"{tabTre}var {instanceModelName} = await _context.{tableViewName}.FindAsync(id);");
                        //sb.AppendLine($"{tabTre}_context.{tableViewName}.Remove({instanceModelName});");
                        //sb.AppendLine($"{tabTre}await _context.SaveChangesAsync();");
                        //sb.AppendLine($"{tabTre}return RedirectToAction(nameof(Index));");

                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"{tabTwo}");

                        sb.AppendLine($"        /// <summary>");
                        sb.AppendLine($"        /// 批量删除数据");
                        sb.AppendLine($"        /// POST: {areaName}/{controllerName}/BatchDelete/5,7");
                        sb.AppendLine($"        /// </summary>");
                        sb.AppendLine($"        /// <param name=\"id\">数据编号集合</param>");
                        sb.AppendLine($"        /// <returns></returns>");
                        sb.AppendLine($"        [HttpPost]");
                        sb.AppendLine($"        public async Task<IActionResult> BatchDelete(string? id)");
                        sb.AppendLine($"        {{");
                        sb.AppendLine($"            var method = $\"{{RouteData.Values[\"controller\"]}}.{{RouteData.Values[\"action\"]}}\";");
                        sb.AppendLine($"            using var transaction = await _context.Database.BeginTransactionAsync();");
                        sb.AppendLine($"            ");
                        sb.AppendLine($"            try");
                        sb.AppendLine($"            {{");
                        sb.AppendLine($"                if (string.IsNullOrEmpty(id))");
                        sb.AppendLine($"                {{");
                        sb.AppendLine($"                    return Json(new {{ success = false, message = \"要删除的{baseTableDesc}数据主键集合为空！\" }});");
                        sb.AppendLine($"                }}");
                        sb.AppendLine($"                var idarr = id.Trim().Split(',');");
                        sb.AppendLine($"                foreach (var idd in idarr)");
                        sb.AppendLine($"                {{");
                        sb.AppendLine($"                    var {instanceModelName} = await _context.{tableDbSetName}.FindAsync(int.Parse(idd));");
                        sb.AppendLine($"                    if ({instanceModelName} != null) _context.{tableDbSetName}.Remove({instanceModelName});");
                        sb.AppendLine($"                }}");
                        sb.AppendLine($"                await _context.SaveChangesAsync();");
                        sb.AppendLine($"                await transaction.CommitAsync(); // 事务提交");
                        sb.AppendLine($"                return Json(new {{ success = true, message = \"{baseTableDesc}数据删除成功！\" }});");
                        sb.AppendLine($"            }}");
                        sb.AppendLine($"            catch (Exception ex)");
                        sb.AppendLine($"            {{");
                        sb.AppendLine($"                await transaction.RollbackAsync(); // 事务回滚");
                        sb.AppendLine($"                _logger.LogError($\"{{method}}：{{ex}}\");");
                        sb.AppendLine($"                return Json(new {{ success = false, message = ex.Message }});");
                        sb.AppendLine($"            }}");
                        sb.AppendLine($"        }}");
                        sb.AppendLine($"");

                        sb.AppendLine($"{tabTwo}private bool {tableModelName}Exists(int id)");
                        sb.AppendLine($"{tabTwo}{{");
                        sb.AppendLine($"{tabTre}return _context.{tableDbSetName}.Any(e => e.Id == id);");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"");

                        if (isTree)
                        {
                            sb.AppendLine($"        #region {baseTableDesc}树结构数据");
                            sb.AppendLine($"");
                            sb.AppendLine($"        /// <summary>");
                            sb.AppendLine($"        /// {baseTableDesc}树结构数据");
                            sb.AppendLine($"        /// GET: {areaName}/{controllerName}/TreeData");
                            sb.AppendLine($"        /// </summary>");
                            sb.AppendLine($"        /// <param name=\"id\">ID</param>");
                            sb.AppendLine($"        /// <param name=\"selectId\">选中节点ID</param>");
                            sb.AppendLine($"        /// <returns></returns>");
                            sb.AppendLine($"        public ActionResult TreeData(string id, string selectId)");
                            sb.AppendLine($"        {{");
                            sb.AppendLine($"            var method = $\"{{RouteData.Values[\"controller\"]}}.{{RouteData.Values[\"action\"]}}\";");
                            sb.AppendLine($"            ");
                            sb.AppendLine($"            try");
                            sb.AppendLine($"            {{");

                            if (dbType == DBType.SqlServer)
                            {
                                sb.AppendLine($"                var strSql = string.Format(@\";WITH Tb AS (");
                                sb.AppendLine($"	            SELECT Id, ISNULL(PId, '00000000-0000-0000-0000-000000000000') AS PId, WorkNo, Sort, Title, 0 AS NodeLevel, Sort AS PSort");
                                sb.AppendLine($"	            FROM dbo.{tableName} ");
                                sb.AppendLine($"	            WHERE (ProjectId = 'C88478D7-0AF3-43A2-83AD-AFC2F8FBFEA0')");
                                sb.AppendLine($"	            AND (PId IS NULL OR ISNULL(PId, '00000000-0000-0000-0000-000000000000') = '00000000-0000-0000-0000-000000000000')");
                                sb.AppendLine($"	            AND (LEN(WorkNo) > 0)");
                                sb.AppendLine($"	            UNION ALL");
                                sb.AppendLine($"	            SELECT d.Id, d.PId, d.WorkNo, d.Sort, d.Title, t.NodeLevel + 1 AS NodeLevel, t.Sort AS PSort");
                                sb.AppendLine($"	            FROM dbo.{tableName} d");
                                sb.AppendLine($"	            INNER JOIN Tb t ON t.Id = d.PId");
                                sb.AppendLine($"            )");
                                sb.AppendLine($"            SELECT CAST(a.Id AS CHAR(36)) AS Id, CAST(a.PId AS CHAR(36)) AS PId, a.Title AS [Text], a.NodeLevel");
                                sb.AppendLine($"            , (SELECT COUNT(*) FROM Tb WHERE Tb.PId = a.Id) AS ChildCount");
                                sb.AppendLine($"            , CASE WHEN a.Id = '00000000-0000-0000-0000-000000000000' THEN 1 ELSE 0 END AS IsChecked");
                                sb.AppendLine($"            FROM Tb a");
                                sb.AppendLine($"            WHERE (a.NodeLevel < 2)");
                                sb.AppendLine($"            ORDER BY a.NodeLevel, a.PSort, a.Sort, a.WorkNo;");
                                sb.AppendLine($"            ;\");");
                                sb.AppendLine($"");
                            }

                            if (dbType == DBType.MySql)
                            {
                                sb.AppendLine($"                var strSql = string.Format(@\"");
                                sb.AppendLine($"                    CALL WITH_EMULATOR(");
                                sb.AppendLine($"                    'TREETABLE_EXTENDED',");
                                sb.AppendLine($"                    '");
                                sb.AppendLine($"                      SELECT Id, PId, NAME AS TEXT, 0 AS NodeLevel, SortNumber, 0 AS PSortNumber");
                                sb.AppendLine($"                      FROM {tableName} WHERE (PId = 0)");
                                sb.AppendLine($"                    ',");
                                sb.AppendLine($"                    '");
                                sb.AppendLine($"                      SELECT m.Id, m.PId, m.NAME AS TEXT, e.NodeLevel + 1 AS NodeLevel");
                                sb.AppendLine($"                      , m.SortNumber, e.SortNumber AS PSortNumber");
                                sb.AppendLine($"                      FROM {tableName} m ");
                                sb.AppendLine($"                      INNER JOIN TREETABLE_EXTENDED e ON e.Id=m.PId");
                                sb.AppendLine($"                    ',");
                                sb.AppendLine($"                    'SELECT * FROM TREETABLE_EXTENDED ORDER BY PSortNumber, SortNumber',");
                                sb.AppendLine($"                    0,");
                                sb.AppendLine($"                    ''");
                                sb.AppendLine($"                    );\");");
                            }

                            sb.AppendLine($"                List<TreeDto> treeDtos = _context.Database.SqlQuery<TreeDto>(strSql)?.ToList();");
                            sb.AppendLine($"");
                            sb.AppendLine($"                //var defautlGuid = \"00000000-0000-0000-0000-000000000000\";");
                            sb.AppendLine($"                List<TreeView> treeList = base.TreeViewMethod(treeDtos);");
                            sb.AppendLine($"");
                            sb.AppendLine($"                return Json(new {{ success = true, Data = treeList }});");
                            sb.AppendLine($"            }}");
                            sb.AppendLine($"            catch (Exception ex)");
                            sb.AppendLine($"            {{");
                            sb.AppendLine($"                _logger.LogError($\"{{method}}：{{ex}}\");");
                            sb.AppendLine($"                return Json(new {{ success = false, message = ex.Message }});");
                            sb.AppendLine($"            }}");
                            sb.AppendLine($"        }}");
                            sb.AppendLine($"");
                            sb.AppendLine($"        #endregion");
                            sb.AppendLine($"");
                            sb.AppendLine($"        #region {baseTableDesc}树结构视图");
                            sb.AppendLine($"");
                            sb.AppendLine($"        /// <summary>");
                            sb.AppendLine($"        /// {baseTableDesc}树结构视图");
                            sb.AppendLine($"        /// GET: {areaName}/{controllerName}/TreeList/");
                            sb.AppendLine($"        /// </summary>");
                            sb.AppendLine($"        /// <param name=\"mid\">菜单ID</param>");
                            sb.AppendLine($"        /// <param name=\"mapname\">菜单路径</param>");
                            sb.AppendLine($"        /// <returns></returns>");
                            sb.AppendLine($"        public IActionResult TreeList(int? mid, string? mapname)");
                            sb.AppendLine($"        {{");
                            sb.AppendLine($"            ViewData[\"Title\"] = \"{baseTableDesc}\";");
                            sb.AppendLine($"            if (string.IsNullOrEmpty(mapname))");
                            sb.AppendLine($"            {{");
                            sb.AppendLine($"                if (mid.HasValue)");
                            sb.AppendLine($"                {{");
                            sb.AppendLine($"                    mapname = DataCache.Menus?.Where(m => m.Id == mid.Value).FirstOrDefault()?.MapName;");
                            sb.AppendLine($"                }}");
                            sb.AppendLine($"                if (string.IsNullOrEmpty(mapname)) mapname = \"{areaName}.{baseTableDesc}\";");
                            sb.AppendLine($"            }}");
                            sb.AppendLine($"            var mapArr = mapname.ToString().Split('.');");
                            sb.AppendLine($"            ViewBag.MapName = mapArr;");
                            sb.AppendLine($"            if (mapArr.Length > 0) ViewData[\"Title\"] = mapArr[^1];");
                            sb.AppendLine($"            {tableDtoName} dto = new();");
                            sb.AppendLine($"            var model = _mapper.Map<{tableViewModelName}>(dto);");
                            sb.AppendLine($"            //model.Projects = ViewCache.Projects;");
                            sb.AppendLine($"            //model.Users = ViewCache.Users;");
                            sb.AppendLine($"            //model.ProjectId = ProjectId;");
                            sb.AppendLine($"            return View(model);");
                            sb.AppendLine($"        }}");
                            sb.AppendLine($"");
                            sb.AppendLine($"        #endregion");
                            sb.AppendLine($"		");
                            sb.AppendLine($"");
                        }
                        else
                        {
                            sb.AppendLine($"");
                            sb.AppendLine($"        #region {baseTableDesc}列表数据视图");
                            sb.AppendLine($"");
                            sb.AppendLine($"        /// <summary>");
                            sb.AppendLine($"        /// {baseTableDesc}列表数据视图");
                            sb.AppendLine($"        /// GET: {areaName}/{controllerName}/TableList");
                            sb.AppendLine($"        /// </summary>");
                            sb.AppendLine($"        /// <param name=\"mid\">菜单ID</param>");
                            sb.AppendLine($"        /// <param name=\"mapname\">菜单路径</param>");
                            sb.AppendLine($"        /// <returns></returns>");
                            sb.AppendLine($"        public IActionResult TableList(int? mid, string? mapname)");
                            sb.AppendLine($"        {{");

                            sb.AppendLine($"            ViewData[\"Title\"] = \"{baseTableDesc}\";");
                            sb.AppendLine($"            if (string.IsNullOrEmpty(mapname))");
                            sb.AppendLine($"            {{");
                            sb.AppendLine($"                if (mid.HasValue)");
                            sb.AppendLine($"                {{");
                            sb.AppendLine($"                    mapname = DataCache.Menus?.Where(m => m.Id == mid.Value).FirstOrDefault()?.MapName;");
                            sb.AppendLine($"                }}");
                            sb.AppendLine($"                if (string.IsNullOrEmpty(mapname)) mapname = \"{areaName}.{baseTableDesc}\";");
                            sb.AppendLine($"            }}");
                            sb.AppendLine($"            var mapArr = mapname.ToString().Split('.');");
                            sb.AppendLine($"            ViewBag.MapName = mapArr;");
                            sb.AppendLine($"            if (mapArr.Length > 0) ViewData[\"Title\"] = mapArr[^1];");

                            sb.AppendLine($"            {tableDtoName} dto = new();");
                            sb.AppendLine($"            var model = _mapper.Map<{tableViewModelName}>(dto);");
                            //sb.AppendLine($"            //model.Projects = ViewCache.Projects;");
                            //sb.AppendLine($"            //model.Users = ViewCache.Users;");
                            //sb.AppendLine($"            //model.ProjectId = ProjectId;");
                            sb.AppendLine($"            return View(model);");
                            sb.AppendLine($"        }}");
                            sb.AppendLine($"");
                            sb.AppendLine($"        #endregion ");
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"        #region {baseTableDesc}分页数据查询");
                        sb.AppendLine($"");
                        sb.AppendLine($"        /// <summary>");
                        sb.AppendLine($"        /// {baseTableDesc}分页数据查询");
                        sb.AppendLine($"        /// GET: {areaName}/{controllerName}/PageList");
                        sb.AppendLine($"        /// </summary>");
                        sb.AppendLine($"        /// <param name=\"pageNumber\">当前页码</param>");
                        sb.AppendLine($"        /// <param name=\"pageSize\">分页大小</param>");
                        sb.AppendLine($"        /// <param name=\"title\">检索关键词</param>");
                        if (isTree)
                        {
                            sb.AppendLine($"        /// <param name=\"id\">父级ID</param>");
                        }
                        sb.AppendLine($"        /// <returns></returns>");
                        var dateParameters = string.Empty;
                        if (columnLength > 10)
                        {
                            dateParameters = ", string? startDate, string? endDate";
                        }
                        if (isTree)
                        {
                            sb.AppendLine($"        public async Task<JsonResult> PageList(int? pageNumber, int? pageSize, Guid? id, string? title{dateParameters})");
                        }
                        else
                        {
                            sb.AppendLine($"        public async Task<JsonResult> PageList(int? pageNumber, int? pageSize, string? title{dateParameters})");
                        }

                        sb.AppendLine($"        {{");

                        sb.AppendLine($"            var method = $\"{{RouteData.Values[\"controller\"]}}.{{RouteData.Values[\"action\"]}}\";");
                        sb.AppendLine($"            ");
                        sb.AppendLine($"            List<{tableDtoName}>? rows = new ();");

                        sb.AppendLine($"            try");
                        sb.AppendLine($"            {{");
                        sb.AppendLine($"                #region 参数处理");
                        sb.AppendLine($"                ");

                        sb.AppendLine($"                var urlDecode = HttpUtility.UrlDecode(title);");
                        sb.AppendLine($"                if (urlDecode != null) title = title == null ? \"\" : urlDecode.Trim();");
                        sb.AppendLine($"");
                        sb.AppendLine($"                string strQry = \"\";");
                        sb.AppendLine($"");
                        if (isTree)
                        {
                            sb.AppendLine($"                if (id.HasValue)");
                            sb.AppendLine($"                {{");
                            sb.AppendLine($"                    strQry += string.Format(@\" AND ({alternativeName}.PId = '{{0}}')\", id.Value);");
                            sb.AppendLine($"                }}");
                            sb.AppendLine($"                else");
                            sb.AppendLine($"                {{");
                            sb.AppendLine($"                    strQry += string.Format(@\" AND ({alternativeName}.PId IS NULL OR {alternativeName}.PId = '')\", title);");
                            sb.AppendLine($"                }}");
                            sb.AppendLine($"");
                        }

                        sb.AppendLine($"                if (!string.IsNullOrEmpty(title))");
                        sb.AppendLine($"                {{");
                        sb.AppendLine($"                    strQry += string.Format(@\" AND ({alternativeName}.Title LIKE '%{{0}}%' OR {alternativeName}.ABCDEF LIKE '%{{0}}%')\", title);");
                        sb.AppendLine($"                }}");

                        if (columnLength > 10)
                        {
                            sb.AppendLine($"                // 起止日期");

                            //sb.AppendLine($"                if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))");
                            //sb.AppendLine($"                {{");
                            //sb.AppendLine($"                    strQry += string.Format(@\" AND (unix_timestamp({alternativeName}.`CreateTime`) >= unix_timestamp('{{0}}') and unix_timestamp({alternativeName}.`CreateTime`) < unix_timestamp(DATE_ADD('{{1}}', INTERVAL 1 DAY)))\", startDate, endDate);");
                            //sb.AppendLine($"                }}");
                            //sb.AppendLine($"                if (!string.IsNullOrEmpty(startDate) && string.IsNullOrEmpty(endDate))");
                            //sb.AppendLine($"                {{");
                            //sb.AppendLine($"                    strQry += string.Format(@\" AND (unix_timestamp({alternativeName}.`CreateTime`) >= unix_timestamp('{{0}}'))\", startDate, endDate);");
                            //sb.AppendLine($"                }}");
                            //sb.AppendLine($"                if (string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))");
                            //sb.AppendLine($"                {{");
                            //sb.AppendLine($"                    strQry += string.Format(@\" AND (unix_timestamp({alternativeName}.`CreateTime`) < unix_timestamp(DATE_ADD('{{1}}', INTERVAL 1 DAY)))\", startDate, endDate);");
                            //sb.AppendLine($"                }}");

                            sb.AppendLine($"                strQry += DateQuerySql(startDate, endDate, \"{alternativeName}.`CreateTime`\");");
                        }

                        sb.AppendLine($"                ");
                        sb.AppendLine($"                #endregion");

                        sb.AppendLine($"");
                        sb.AppendLine($"                #region 分页及页码数据处理处理");
                        sb.AppendLine($"");
                        sb.AppendLine($"                if (!pageNumber.HasValue) pageNumber = 1;");
                        sb.AppendLine($"                if (!pageSize.HasValue) pageSize = 10;");
                        if (dbType == DBType.SqlServer)
                        {
                            sb.AppendLine($"                var min = (pageNumber - 1) * pageSize + 1;");
                            sb.AppendLine($"                var max = pageNumber * pageSize;");
                        }
                        if (dbType == DBType.MySql)
                        {
                            sb.AppendLine($"                var skip = (pageNumber.Value - 1) * pageSize.Value;");
                        }
                        sb.AppendLine($"");
                        sb.AppendLine($"                #endregion");
                        sb.AppendLine($"");

                        if (dbType == DBType.SqlServer)
                        {
                            sb.AppendLine($"                var strSql = string.Format(@\"");
                            sb.AppendLine($"	                ;WITH PageTb AS (");
                            sb.AppendLine($"		                SELECT ROW_NUMBER() OVER (ORDER BY {alternativeName}.Id DESC) RowNumber");
                            sb.AppendLine($"			                , {columns}");
                            sb.AppendLine($"		                FROM dbo.[{tableName}] {alternativeName} WHERE (1 = 1) ");
                            sb.AppendLine($"		                 {{2}} ");
                            sb.AppendLine($"		                )");
                            sb.AppendLine($"	                SELECT * ");
                            sb.AppendLine($"	                FROM PageTb a");
                            sb.AppendLine($"	                CROSS JOIN (SELECT MAX(RowNumber) AS RecordCount FROM PageTb) AS b ");
                            sb.AppendLine($"	                WHERE (a.RowNumber BETWEEN {{0}} AND {{1}});");
                            sb.AppendLine($"                 \", min, max, strQry);");
                            sb.AppendLine($"");
                            sb.AppendLine($"                var rows = await Db.Ado.SqlQueryAsync<{tableDtoName}>(strSql);"); // _context.Database.SqlQuery<{tableDtoName}>(strSql)?.ToList();
                            sb.AppendLine($"");
                            sb.AppendLine($"                return Json(new {{ success = true, total = rows?.Count > 0 ? rows[0].RecordCount : 0, rows }});");
                        }
                        if (dbType == DBType.MySql)
                        {
                            //sb.AppendLine($"                var strSql = string.Format(@\"");
                            //sb.AppendLine($"                    SELECT {alternativeName}.*");
                            //sb.AppendLine($"                    FROM `{tableName}` {alternativeName}");
                            //sb.AppendLine($"                    WHERE (1=1){{0}};");
                            //sb.AppendLine($"                 \",  strQry);");
                            //sb.AppendLine($"");
                            //sb.AppendLine($"                int total = 0; // 查询分页，只支持简单查询的Sql，不能是存储过程和一些特殊逻的Sql。");
                            //sb.AppendLine($"                var rows = Db.SqlQueryable<{tableDtoName}>(strSql).OrderBy(\"{alternativeName}.{keyName} DESC\").ToPageList(pageNumber ?? 1, pageSize ?? 10, ref total);");
                            //sb.AppendLine($"                return Json(new {{ success = true, total, rows }});");

                            sb.AppendLine($"                #region 数据查询");
                            sb.AppendLine($"");
                            sb.AppendLine($"                var strSql = string.Format($@\"");
                            sb.AppendLine($"                    SELECT {alternativeName}.*");
                            sb.AppendLine($"                    FROM `{tableName}` {alternativeName}");
                            sb.AppendLine($"                    WHERE (1=1){{strQry}}");
                            sb.AppendLine($"                    ORDER BY {alternativeName}.`Id` DESC LIMIT {{skip}}, {{pageSize}};");
                            sb.AppendLine($"                 \");");
                            sb.AppendLine($"");
                            sb.AppendLine($"                rows = await Db.Ado.SqlQueryAsync<{tableDtoName}>(strSql);");
                            sb.AppendLine($"");
                            sb.AppendLine($"                #endregion");
                            sb.AppendLine($"");
                            sb.AppendLine($"                #region 数量查询");
                            sb.AppendLine($"");
                            sb.AppendLine($"                strSql = string.Format($@\"");
                            sb.AppendLine($"                    SELECT COUNT(*)");
                            sb.AppendLine($"                    FROM `{tableName}` {alternativeName}");
                            sb.AppendLine($"                    WHERE (1=1){{strQry}};");
                            sb.AppendLine($"                 \");");
                            sb.AppendLine($"");
                            sb.AppendLine($"                int? total = await Db.Ado.GetIntAsync(strSql);");
                            sb.AppendLine($"");
                            sb.AppendLine($"                #endregion");
                            sb.AppendLine($"");
                            sb.AppendLine($"                return Json(new {{success = true, total, rows }});");

                        }

                        //if (dbType == DBType.SqlServer)
                        //{
                        //}
                        //if (dbType == DBType.MySql)
                        //{
                        //}

                        sb.AppendLine($"            }}");
                        sb.AppendLine($"            catch (Exception ex)");
                        sb.AppendLine($"            {{");
                        sb.AppendLine($"                _logger.LogError($\"{{method}}：{{ex}}\");");
                        sb.AppendLine($"                return Json(new {{ success = false, total = 0, rows, message = ex.Message }});");
                        sb.AppendLine($"            }}");
                        sb.AppendLine($"        }}");
                        sb.AppendLine($"");
                        sb.AppendLine($"        #endregion");
                        sb.AppendLine($"");

                        sb.AppendLine($"        #region {baseTableDesc}数据保存");
                        sb.AppendLine($"");
                        sb.AppendLine($"        /// <summary>");
                        sb.AppendLine($"        /// {baseTableDesc}数据保存");
                        sb.AppendLine($"        /// POST: {areaName}/{controllerName}/Save");
                        sb.AppendLine($"        /// </summary>");
                        sb.AppendLine($"        /// <param name=\"{instanceModelName}\">{baseTableDesc}</param>");
                        sb.AppendLine($"        /// <returns></returns>");
                        //[Bind(\"{columns}\")]
                        sb.AppendLine($"        public async Task<IActionResult> Save([FromBody] {tableModelName} {instanceModelName})");
                        sb.AppendLine($"        {{");
                        sb.AppendLine($"            var method = $\"{{RouteData.Values[\"controller\"]}}.{{RouteData.Values[\"action\"]}}\";");
                        sb.AppendLine($"            ");
                        sb.AppendLine($"            try");
                        sb.AppendLine($"            {{");
                        sb.AppendLine($"                string flag;");

                        #region 数据保存判断条件

                        var createCondition = string.Empty;
                        var createKey = string.Empty;
                        if (dbType == DBType.SqlServer)
                        {
                            if (keyDataType == "uniqueidentifier")
                            {
                                createKey = $"{instanceModelName}.Id = Guid.NewGuid();";
                                createCondition = $" || {instanceModelName}.Id == Guid.Empty";
                            }
                            if (keyDataType == "int")
                                createCondition = $" || {instanceModelName}.Id == 0";
                        }
                        if (dbType == DBType.MySql)
                        {
                            if (keyDataType == "varchar")
                            {
                                createKey = $"{instanceModelName}.Id = Guid.NewGuid().ToString();";
                                createCondition = $" || string.IsNullOrEmpty({instanceModelName}.Id";
                            }
                            if (keyDataType == "int")
                                createCondition = $" || {instanceModelName}.Id == 0";
                        }

                        #endregion

                        sb.AppendLine($"                if (!{tableModelName}Exists({instanceModelName}.Id){createCondition})");
                        sb.AppendLine($"                {{");
                        sb.AppendLine($"                    flag = \"添加\";");
                        sb.AppendLine($"");
                        if (!string.IsNullOrEmpty(createKey))
                        {
                            sb.AppendLine($"                    {createKey}"); // GUID主键
                        }
                        sb.AppendLine($"                    {instanceModelName}.CreatorId = base.CurrentUser?.Id;");
                        if (hasCreateTime)
                        {
                            sb.AppendLine($"                    {instanceModelName}.CreateTime = DateTime.Now;");
                        }
                        sb.AppendLine($"                    await _context.AddAsync({instanceModelName});");
                        sb.AppendLine($"                }}");
                        sb.AppendLine($"                else");
                        sb.AppendLine($"                {{");
                        sb.AppendLine($"                    flag = \"修改\";");
                        sb.AppendLine($"");
                        sb.AppendLine($"                    {instanceModelName}.ModifierId = base.CurrentUser?.Id;");
                        if (hasUpdateTime)
                        {
                            sb.AppendLine($"                    {instanceModelName}.ModifiedTime = DateTime.Now;");
                        }
                        sb.AppendLine($"                    _context.Update({instanceModelName});");
                        sb.AppendLine($"                }}");
                        sb.AppendLine($"");
                        sb.AppendLine($"                await _context.SaveChangesAsync();");
                        sb.AppendLine($"");
                        sb.AppendLine($"                return Json(new {{ success = true, message = $\"{baseTableDesc}数据{{flag}}成功!\" }});");
                        sb.AppendLine($"");
                        sb.AppendLine($"            }}");
                        sb.AppendLine($"            catch (Exception ex)");
                        sb.AppendLine($"            {{");
                        sb.AppendLine($"                _logger.LogError($\"{{method}}：{{ex}}\");");
                        sb.AppendLine($"                return Json(new {{ success = false, message = ex.Message }});");
                        sb.AppendLine($"            }}");
                        sb.AppendLine($"        }}");
                        sb.AppendLine($"");
                        sb.AppendLine($"        #endregion");

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabOne}}}");
                        sb.AppendLine($"}}");

                        #region 注释

                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTwo}#region {baseTableDesc}视图");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTwo}/// <summary>");
                        //sb.AppendLine($"{tabTwo}/// {baseTableDesc}视图");
                        //sb.AppendLine($"{tabTwo}/// GET: {areaName}/{controllerName}");
                        //sb.AppendLine($"{tabTwo}/// </summary>");
                        //sb.AppendLine($"{tabTwo}/// <returns></returns>");
                        //sb.AppendLine($"{tabTwo}public ActionResult Index()");
                        //sb.AppendLine($"{tabTwo}{{");
                        //sb.AppendLine($"{tabTre}if (CurrentUser == null)");
                        //sb.AppendLine($"{tabTre}{{");
                        //sb.AppendLine($"{tabTre}    RedirectToAction(\"LogOut\", \"Account\", new {{ area = \"\" }});");
                        //sb.AppendLine($"{tabTre}}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}#region 下拉框数据");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}//ViewBag.UserRoleLit = SelectDataCache.UserRoleList;");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}#endregion");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}{tableName} model = new {tableName}();");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}return View(model);");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTwo}#endregion");
                        //sb.AppendLine($"");

                        //sb.AppendLine($"#region 批量填充库表随机数据");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"/// <summary>");
                        //sb.AppendLine($"/// 批量填充库表随机数据");
                        //sb.AppendLine($"/// GET: {areaName}/{controllerName}/SqlBulkRandomData");
                        //sb.AppendLine($"/// </summary>");
                        //sb.AppendLine($"/// <returns></returns>");
                        //sb.AppendLine($"public ActionResult SqlBulkRandomData()");
                        //sb.AppendLine($"{{");
                        //sb.AppendLine($"	try");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		bll.SqlBulkRandomData(50);");
                        //sb.AppendLine($"		var result = new {{ success = true, message = \"批量填充库表随机数据成功\" }};");
                        //sb.AppendLine($"		return Json(result, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"	catch (Exception ex)");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"#endregion");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"#region 获取{baseTableDesc}分页数据");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"/// <summary>");
                        //sb.AppendLine($"/// 获取{baseTableDesc}分页数据");
                        //sb.AppendLine($"/// {areaName}/{controllerName}/PageList/");
                        //sb.AppendLine($"/// </summary>");
                        //sb.AppendLine($"/// <param name=\"pageNumber\">当前页码</param>");
                        //sb.AppendLine($"/// <param name=\"pageSize\">分页大小</param>");
                        //sb.AppendLine($"/// <param name=\"title\">标题检索</param>");
                        //sb.AppendLine($"/// <returns></returns>");
                        //sb.AppendLine($"public ActionResult PageList(int pageNumber, int pageSize, string title)");
                        //sb.AppendLine($"{{");
                        //sb.AppendLine($"	var urlDecode = HttpUtility.UrlDecode(title);");
                        //sb.AppendLine($"	if (urlDecode != null) title = title == null ? \"\" : urlDecode.Trim();");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"	try");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		var paramList = new Dictionary<string, string>");
                        //sb.AppendLine($"		{{");
                        //sb.AppendLine($"			{{\"Name\", title}},");
                        //sb.AppendLine($"			{{\"PageSize\", pageSize.ToString()}},");
                        //sb.AppendLine($"			{{\"PageIndex\", pageNumber.ToString()}}");
                        //sb.AppendLine($"		}};");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"		var list = bll.PageList(paramList);");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"		var result = new {{ success = true, total = list.Count > 0 ? list[0].RecordCount : 0, rows = list }};");
                        //sb.AppendLine($"		return Json(result, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"	catch (Exception ex)");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		var result = new {{ success = false, total = 0, rows = new List<Hashtable>(), ex.Message }};");
                        //sb.AppendLine($"		return Json(result, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"#endregion");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"#region 添加或编辑{baseTableDesc}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"/// <summary>");
                        //sb.AppendLine($"///     添加或编辑{baseTableDesc}");
                        //sb.AppendLine($"///     GET: {areaName}/{controllerName}/Save/");
                        //sb.AppendLine($"/// </summary>");
                        //sb.AppendLine($"/// <param name=\"json\">{baseTableDesc}Json数据</param>");
                        //sb.AppendLine($"/// <returns></returns>");
                        //sb.AppendLine($"[Authorize]");
                        //sb.AppendLine($"public ActionResult Save(string json)");
                        //sb.AppendLine($"{{");
                        //sb.AppendLine($"	if (CurrentUser == null)");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		return RedirectToAction(\"LogOut\", \"Account\", new {{ area = \"\" }});");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"	try");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		int rst = 0, saveType = 0; // 数据库影响行数，存储类型：0-添加；1-修改");
                        //sb.AppendLine($"		var str{controllerName} = HttpUtility.UrlDecode(json);");
                        //sb.AppendLine($"		var entity = JsonConvert.DeserializeObject<{tableName}>(str{controllerName});");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"		{tableName} model = new {tableName}();");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"		if (entity.Id == Guid.Empty) // 添加");
                        //sb.AppendLine($"		{{");
                        //sb.AppendLine($"			model.Id = Guid.NewGuid();");

                        //foreach (var column in tableColumns.Where(s => s.Name == "State"))
                        //{
                        //    sb.AppendLine($"			model.State = 0; // 数据状态：0-正常；1-禁用；2-删除");
                        //}

                        //sb.AppendLine($"			model.F_CreatorId = CurrentUser.Id; // 创建人ID");
                        //sb.AppendLine($"			model.F_CreateTime = DateTime.Now; // 创建时间                    ");
                        //sb.AppendLine($"		}}");
                        //sb.AppendLine($"		else");
                        //sb.AppendLine($"		{{");
                        //sb.AppendLine($"			saveType = 1;");
                        //sb.AppendLine($"			model = bll.SingleQuery(entity.Id);");
                        //sb.AppendLine($"			model.F_ModifierId = CurrentUser.Id; // 编辑人ID");
                        //sb.AppendLine($"			model.F_ModifiedTime = DateTime.Now; // 编辑时间");
                        //sb.AppendLine($"		}}");
                        //sb.AppendLine($"");

                        //foreach (var column in tableColumns)
                        //{
                        //    //if (column.Queryable == 1) // 可查询字段
                        //    //{
                        //    if (column.IsPK == 1
                        //        || column.Name.IndexOf("CreatorId") > -1
                        //        || column.Name.IndexOf("CreateTime") > -1
                        //        || column.Name.IndexOf("LastModifierId") > -1
                        //        || column.Name.IndexOf("LastModifyTime") > -1
                        //        || column.Name.IndexOf("ModifierId") > -1
                        //        || column.Name.IndexOf("ModifiedTime") > -1)
                        //    {
                        //        sb.AppendLine($"		//model.{column.Name} = entity.{column.Name}; // {column.Comment}");
                        //    }
                        //    else
                        //    {
                        //        sb.AppendLine($"		model.{column.Name} = entity.{column.Name}; // {column.Comment}");
                        //    }
                        //    //}
                        //    //else
                        //    //{
                        //    //    sb.AppendLine($"		//model.{column.Name} = entity.{column.Name}; // {column.Comment}");
                        //    //}
                        //}

                        //sb.AppendLine($"");
                        //sb.AppendLine($"		if (saveType == 0)");
                        //sb.AppendLine($"		{{");
                        //sb.AppendLine($"			rst = bll.Add(model);");
                        //sb.AppendLine($"		}}");
                        //sb.AppendLine($"		else");
                        //sb.AppendLine($"		{{");
                        //sb.AppendLine($"			rst = bll.Update(model);");
                        //sb.AppendLine($"		}}");
                        //sb.AppendLine($"");

                        //#region 长文本处理

                        //foreach (var column in tableColumns)
                        //{
                        //    var columnId = column.Id; // 列Id
                        //    var columnName = column.Name; // 列名
                        //    var columnDesc = column.Comment?.Replace(":", "："); // 列描述【列基本描述：枚举描述】
                        //    
                        //    var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                        //    if (column.IsPK == 1)
                        //    {
                        //        primaryKey = columnName;
                        //    }

                        //    if (column.DataType!.Contains("varchar") && column.Length == -1
                        //    || column.DataType!.Contains("text"))
                        //    {
                        //        sb.AppendLine($"{tabTre}    if (rst > 0 && !string.IsNullOrEmpty(model.{columnName}))");
                        //        sb.AppendLine($"{tabTre}    {{");
                        //        sb.AppendLine($"{tabTre}        bll.ContentSave<{tableName}>(model.{primaryKey}, \"{columnName}\", model.{columnName});");
                        //        sb.AppendLine($"{tabTre}    }}");
                        //    }
                        //}

                        //#endregion

                        //sb.AppendLine($"");
                        //sb.AppendLine($"		var rstMsg = \"{baseTableDesc}\" + (saveType == 0 ? \"添加\" : \"修改\") + (rst > 0 ? \"成功!\" : \"失败！\");");
                        //sb.AppendLine($"		return Json(new {{ success = rst > 0, Message = rstMsg }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"	catch (Exception ex)");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		logger.Error(ex.Message);");
                        //sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"#endregion");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"#region 物理删除数据");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"/// <summary>");
                        //sb.AppendLine($"/// 删除数据");
                        //sb.AppendLine($"/// POST: {areaName}/{controllerName}/Delete");
                        //sb.AppendLine($"/// </summary>");
                        //sb.AppendLine($"/// <param name=\"id\">数据主键</param>");
                        //sb.AppendLine($"/// <returns></returns>");
                        //sb.AppendLine($"[HttpPost]");
                        //sb.AppendLine($"public ActionResult Delete(string id)");
                        //sb.AppendLine($"{{");
                        //sb.AppendLine($"	try");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		if (string.IsNullOrEmpty(id))");
                        //sb.AppendLine($"		{{");
                        //sb.AppendLine($"			return Json(new {{ success = false, message = \"要删除的数据主键为空！\" }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"		}}");
                        //sb.AppendLine($"		var rst = bll.Delete(new Guid(id));");
                        //sb.AppendLine($"		return Json(new {{ success = true, message = $\"{baseTableDesc}数据删除{{(rst > 0 ? \"成功\" : \"失败\")}}！\" }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"	catch (Exception ex)");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"/// <summary>");
                        //sb.AppendLine($"/// 批量删除数据");
                        //sb.AppendLine($"/// POST: {areaName}/{controllerName}/BatchDelete");
                        //sb.AppendLine($"/// </summary>");
                        //sb.AppendLine($"/// <param name=\"ids\">数据编号集合</param>");
                        //sb.AppendLine($"/// <returns></returns>");
                        //sb.AppendLine($"[HttpPost]");
                        //sb.AppendLine($"public ActionResult BatchDelete(string ids)");
                        //sb.AppendLine($"{{");
                        //sb.AppendLine($"	try");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		if (string.IsNullOrEmpty(ids))");
                        //sb.AppendLine($"		{{");
                        //sb.AppendLine($"			return Json(new {{ success = false, message = \"要删除的数据主键集合为空！\" }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"		}}");
                        //sb.AppendLine($"		bll.BatchDelete(ids);");
                        //sb.AppendLine($"		return Json(new {{ success = true, message = \"{baseTableDesc}数据删除成功！\" }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"	catch (Exception ex)");
                        //sb.AppendLine($"	{{");
                        //sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //sb.AppendLine($"	}}");
                        //sb.AppendLine($"}}");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"#endregion");
                        //sb.AppendLine($"");

                        //if (isLogicalDelete)
                        //{
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"#region 逻辑删除数据");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 逻辑删除数据");
                        //    sb.AppendLine($"/// POST: {areaName}/{controllerName}/LogicalDelete");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"/// <param name=\"id\">数据主键</param>");
                        //    sb.AppendLine($"/// <returns></returns>");
                        //    sb.AppendLine($"[HttpPost]");
                        //    sb.AppendLine($"public ActionResult LogicalDelete(string id)");
                        //    sb.AppendLine($"{{");
                        //    sb.AppendLine($"	try");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		if (string.IsNullOrEmpty(id))");
                        //    sb.AppendLine($"		{{");
                        //    sb.AppendLine($"			return Json(new {{ success = false, message = \"要逻辑删除的数据主键为空！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"		}}");
                        //    sb.AppendLine($"		var rst = bll.ChangeState(new Guid(id), DataStatus.Deleted);");
                        //    sb.AppendLine($"		return Json(new {{ success = true, message = $\"{baseTableDesc}数据逻辑删除{{(rst > 0 ? \"成功\" : \"失败\")}}！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"	catch (Exception ex)");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 逻辑删除数据");
                        //    sb.AppendLine($"/// POST: {areaName}/{controllerName}/BatchLogicalDelete");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"/// <param name=\"ids\">数据编号集合</param>");
                        //    sb.AppendLine($"/// <returns></returns>");
                        //    sb.AppendLine($"[HttpPost]");
                        //    sb.AppendLine($"public ActionResult BatchLogicalDelete(string ids)");
                        //    sb.AppendLine($"{{");
                        //    sb.AppendLine($"	try");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		if (string.IsNullOrEmpty(ids))");
                        //    sb.AppendLine($"		{{");
                        //    sb.AppendLine($"			return Json(new {{ success = false, message = \"要逻辑删除的数据主键集合为空！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"		}}");
                        //    sb.AppendLine($"		bll.ChangeState(ids, DataStatus.Deleted);");
                        //    sb.AppendLine($"		return Json(new {{ success = true, message = \"{baseTableDesc}数据逻辑删除成功！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"	catch (Exception ex)");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"#endregion");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"#region 禁用用户数据");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 删除数据");
                        //    sb.AppendLine($"/// POST: {areaName}/{controllerName}/Disable");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"/// <param name=\"id\">数据主键</param>");
                        //    sb.AppendLine($"/// <returns></returns>");
                        //    sb.AppendLine($"[HttpPost]");
                        //    sb.AppendLine($"public ActionResult Disable(string id)");
                        //    sb.AppendLine($"{{");
                        //    sb.AppendLine($"	try");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		if (string.IsNullOrEmpty(id))");
                        //    sb.AppendLine($"		{{");
                        //    sb.AppendLine($"			return Json(new {{ success = false, message = \"要禁用的数据主键为空！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"		}}");
                        //    sb.AppendLine($"		var rst = bll.ChangeState(new Guid(id), DataStatus.Disable);");
                        //    sb.AppendLine($"		return Json(new {{ success = true, message = $\"{baseTableDesc}数据禁用{{(rst > 0 ? \"成功\" : \"失败\")}}！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"	catch (Exception ex)");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"#endregion");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"#region 启用用户数据");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"/// <summary>");
                        //    sb.AppendLine($"/// 启用用户数据");
                        //    sb.AppendLine($"/// POST: {areaName}/{controllerName}/Enable");
                        //    sb.AppendLine($"/// </summary>");
                        //    sb.AppendLine($"/// <param name=\"id\">数据主键</param>");
                        //    sb.AppendLine($"/// <returns></returns>");
                        //    sb.AppendLine($"[HttpPost]");
                        //    sb.AppendLine($"public ActionResult Enable(string id)");
                        //    sb.AppendLine($"{{");
                        //    sb.AppendLine($"	try");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		if (string.IsNullOrEmpty(id))");
                        //    sb.AppendLine($"		{{");
                        //    sb.AppendLine($"			return Json(new {{ success = false, message = \"要启用的数据主键为空！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"		}}");
                        //    sb.AppendLine($"		var rst = bll.ChangeState(new Guid(id), DataStatus.Normal);");
                        //    sb.AppendLine($"		return Json(new {{ success = true, message = $\"{baseTableDesc}数据启用{{(rst > 0 ? \"成功\" : \"失败\")}}！\" }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"	catch (Exception ex)");
                        //    sb.AppendLine($"	{{");
                        //    sb.AppendLine($"		return Json(new {{ success = false, message = ex.Message }}, JsonRequestBehavior.AllowGet);");
                        //    sb.AppendLine($"	}}");
                        //    sb.AppendLine($"}}");
                        //    sb.AppendLine($"");
                        //    sb.AppendLine($"#endregion");
                        //    sb.AppendLine($"");
                        //}

                        //sb.AppendLine($"{tabOne}}}");
                        //sb.AppendLine($"}}");

                        #endregion

                        File.WriteAllText(controllerFilePath, sb.ToString());

                        #endregion

                        #region Views 视图数据对象

                        sb = new StringBuilder();

                        #region 引用文件

                        sb.AppendLine($"using {dtoSpaceName};");
                        sb.AppendLine($"using Microsoft.AspNetCore.Mvc.Rendering;");
                        sb.AppendLine($"using System;");
                        sb.AppendLine($"using System.Collections.Generic;");
                        sb.AppendLine($"using System.ComponentModel;");
                        sb.AppendLine($"using System.ComponentModel.DataAnnotations;");
                        sb.AppendLine($"using System.Linq;");
                        sb.AppendLine($"using System.Reflection;");
                        sb.AppendLine($"using System.Text;");
                        sb.AppendLine($"using System.Threading.Tasks;");
                        sb.AppendLine();

                        #endregion

                        #region 命名空间

                        sb.AppendLine($"namespace {rootSpaceName}.Web.Models");

                        #endregion

                        sb.AppendLine("{");
                        sb.AppendLine($"{tabOne}/// <summary>");
                        sb.AppendLine($"{tabOne}/// {baseTableDesc}视图实体对象");
                        sb.AppendLine($"{tabOne}/// </summary>");
                        sb.AppendLine($"{tabOne}public class {tableViewModelName} : {tableDtoName}");
                        sb.AppendLine($"{tabOne}{{");
                        sb.AppendLine();
                        sb.AppendLine($"{tabOne}}}");
                        sb.AppendLine("}");

                        File.WriteAllText(viewModelFilePath, sb.ToString());

                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"3）生成区域控制器及视图文件输出错误", ex);
                throw;
            }
        }

        #endregion

        #region 4）生成业务逻辑层CS代码

        /// <summary>
        /// 开始创建生成业务逻辑层代码CS文件
        /// Dictionary<string, List<Columns>> tabledicList
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        private void CreateBllFile(string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            string filePath = $"{selectPath}\\Bll\\";
            FileHelper.FilePathCheck(filePath);

            var classSpaceName = txtSpaceName.Text.Trim();
            //string[] classArr = classSpaceName.Split('.');
            //var baseArr = classArr.Take(classArr.Count() - 1).ToArray();string.Join(".", baseArr)
            var baseClassSpace = classSpaceName + ".";
            var baseInterfaceSpace = baseClassSpace + "I";

            foreach (var table in tableList)
            {
                var tableName = table.Name; // 表名
                if (table.Comment == null) continue;
                var tableDesc = table.Comment.Replace(":", "："); // 表描述
                var shortTableDesc = tableDesc.Split('：')[0]; // 表基本描述【描述中冒号前面的部分】

                filePath = $"{selectPath}\\Bll\\{tableName}Bll.cs";

                if (shortTableDesc == tableName)
                {
                    shortTableDesc = $"{{{shortTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                }

                StringBuilder sb = new StringBuilder();

                #region 开发引用命名空间

                sb.AppendLine($"using {baseClassSpace}Common;");
                sb.AppendLine($"using {baseClassSpace}Common.Constants;");
                sb.AppendLine($"using {baseClassSpace}Common.Utilities;");
                sb.AppendLine($"using {baseClassSpace}DalFactory;");
                sb.AppendLine($"using {baseClassSpace}IDal;");
                sb.AppendLine($"using {baseClassSpace}Model;");
                sb.AppendLine($"using {baseClassSpace}Model.BaseModel;");
                sb.AppendLine($"using ChinaSoft.Common.Utility;");
                sb.AppendLine($"using System;");
                sb.AppendLine($"using System.Collections.Generic;");
                sb.AppendLine($"using System.Data;");
                sb.AppendLine($"using System.Linq;");
                sb.AppendLine($"using System.Text;");
                sb.AppendLine($"using System.Threading.Tasks;");
                sb.AppendLine($"");

                #endregion

                //sb.AppendLine($"***************************************************************************");
                //sb.AppendLine($"* {bllName}Bll {shortTableDesc}业务逻辑层代码");
                //sb.AppendLine($"***************************************************************************");
                //sb.AppendLine($"");

                sb.AppendLine($"namespace {txtSpaceName.Text.Trim()}");
                sb.AppendLine($"{{");
                sb.AppendLine($"{tabOne}/// <summary>");
                sb.AppendLine($"{tabOne}/// {tableDesc}业务逻辑层");
                sb.AppendLine($"{tabOne}/// </summary>");
                sb.AppendLine($"{tabOne}public class {tableName}Bll");
                sb.AppendLine($"{tabOne}{{");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 数据服务层初始化");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}private static readonly I{tableName}Dal dal = DataFactory.Create{tableName}Dal();");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#region 实体及列表查询");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 根据主键ID查询实体数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"id\">主键ID</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public {tableName} SingleQuery(Guid id)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.SingleQuery<{tableName}>(id);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 查询全部数据列表");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public List<{tableName}> ListQuery<{tableName}>()");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.ListQuery<{tableName}>();");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 根据条件查询数据列表");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <typeparam name=\"{tableName}\"></typeparam>");
                sb.AppendLine($"{tabTwo}/// <param name=\"sqlwhere\">条件</param>");
                sb.AppendLine($"{tabTwo}/// <param name=\"sqlorderby\">排序</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public List<{tableName}> ListQuery<{tableName}>(string sqlwhere, string sqlorderby)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.ListQuery<{tableName}>(sqlwhere, sqlorderby);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#region 增删改");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 添加实体数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <typeparam name=\"model\">实体数据</typeparam>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public int Add({tableName} model)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.Add(model);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 批量添加数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"list\">实体列表数据</param>");
                sb.AppendLine($"{tabTwo}public void BatchAdd(List<{tableName}> list)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}dal.BatchAdd(list);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 根据主键删除数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"id\">主键ID</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public int Delete(Guid id)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.Delete<{tableName}>(id);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 根据实体列表批量删除数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"list\">实体列表数据</param>");
                sb.AppendLine($"{tabTwo}public void BatchDelete(List<{tableName}> list)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}dal.BatchDelete(list);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 根据主键集合批量删除数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"ids\">主键集合</param>");
                sb.AppendLine($"{tabTwo}public void BatchDelete(string ids)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}dal.BatchDelete<{tableName}>(ids);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 更新/修改数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <typeparam name=\"model\">实体数据</typeparam>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public int Update({tableName} model)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.Update(model);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 批量修改数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"list\">实体列表数据</param>");
                sb.AppendLine($"{tabTwo}public void BatchUpdate(List<{tableName}> list)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}dal.BatchUpdate(list);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#region 变更数据状态");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 根据主键变更数据状态");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"id\">主键</param>");
                sb.AppendLine($"{tabTwo}/// <param name=\"status\">数据状态枚举</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public int ChangeState(Guid id, DataStatus status)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.ChangeState<{tableName}>(id, status);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 批量变更数据状态");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"ids\">主键集合</param>");
                sb.AppendLine($"{tabTwo}/// <param name=\"status\">数据状态枚举</param>");
                sb.AppendLine($"{tabTwo}public void ChangeState(string ids, DataStatus status)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}dal.ChangeState<{tableName}>(ids, status);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#region 获取分页数据列表");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 获取分页数据列表");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"paramList\">分页参数</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public List<{tableName}> PageList(Dictionary<string, string> paramList)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}var list = new List<{tableName}>();");
                sb.AppendLine($"{tabTre}DataTable dt = dal.PageData(paramList);");
                sb.AppendLine($"{tabTre}if (dt != null && dt.Rows.Count > 0)");
                sb.AppendLine($"{tabTre}{{");
                sb.AppendLine($"{tabTre}    list = new DataTableToList<{tableName}>(dt).ToList();");
                sb.AppendLine($"{tabTre}}}");
                sb.AppendLine($"{tabTre}return list;");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#region 批量填充库表随机数据");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 批量填充库表随机数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"rows\">填充数量</param>");
                sb.AppendLine($"{tabTwo}/// <param name=\"connectionString\">数据库连接串</param>");
                sb.AppendLine($"{tabTwo}public void SqlBulkRandomData(int rows)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}dal.SqlBulkRandomData<{tableName}>(rows);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#region 长文本内容处理");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 长文本内容数据保存");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"id\">主键</param>");
                sb.AppendLine($"{tabTwo}/// <param name=\"field\">字段名称</param>");
                sb.AppendLine($"{tabTwo}/// <param name=\"content\">长文本内容</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public int LongContentSave(Guid id, string field, string content)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.LongContentSave<{tableName}>(id, field, content);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 长文本内容数据查询");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"id\">主键</param>");
                sb.AppendLine($"{tabTwo}/// <param name=\"field\">字段名称</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public string LongContentQuery(Guid id, string field)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}return dal.LongContentQuery<{tableName}>(id, field);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabOne}}}");
                sb.AppendLine($"}}");

                File.WriteAllText(filePath, sb.ToString());

            }
        }

        /// <summary>
        /// 生成业务逻辑文件
        /// </summary>
        /// <param name="selectPath"></param>
        /// <param name="tableList"></param>
        /// <param name="columnList"></param>
        private void CreateServiceFile(string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            try
            {

                string servicePath = $"{selectPath}\\Service\\";
                string interfacePath = $"{selectPath}\\IService\\";
                var iocFilePath = $"{selectPath}\\IOCService.cs";

                var classSpaceName = txtSpaceName.Text.Trim();
                //string[] classArr = classSpaceName.Split('.');
                //var baseArr = classArr.Take(classArr.Count() - 1).ToArray();string.Join(".", baseArr)
                var baseClassSpace = classSpaceName + ".";
                var baseInterfaceSpace = baseClassSpace + "I";

                FileHelper.FilePathCheck(servicePath);
                FileHelper.FilePathCheck(interfacePath);

                var className = string.Empty;
                var interfaceName = string.Empty;
                StringBuilder sb = new();
                StringBuilder iocSb = new();

                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 表名
                    if (table.Comment == null) continue;
                    var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                    var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】

                    className = GetClassName(tableName);
                    interfaceName = "I" + className;
                    className += "Service";
                    interfaceName += "Service";

                    iocSb.AppendLine($"builder.Services.AddTransient<{interfaceName}, {className}>(); // {baseTableDesc}服务");

                    var serviceFilePath = $"{servicePath}{className}.cs";
                    var interfaceFilePath = $"{interfacePath}{interfaceName}.cs";

                    if (baseTableDesc == tableName)
                    {
                        baseTableDesc = $"{{{baseTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                    }

                    #region 业务逻辑层输出

                    sb = new StringBuilder();

                    #region 引用文件

                    sb.AppendLine($"using {baseClassSpace}Common;");
                    sb.AppendLine($"using {baseClassSpace}IService;");
                    sb.AppendLine($"using {baseClassSpace}Model.Models;");
                    sb.AppendLine($"using {baseClassSpace}Model.Dtos;");
                    sb.AppendLine($"using {baseClassSpace}Model.Extensions;");
                    sb.AppendLine($"using Microsoft.Data.SqlClient;");
                    sb.AppendLine($"using Microsoft.EntityFrameworkCore;");
                    sb.AppendLine($"using Microsoft.EntityFrameworkCore.Storage;");
                    sb.AppendLine($"using Microsoft.Extensions.Logging;");
                    sb.AppendLine($"using System;");
                    sb.AppendLine($"using System.Collections.Generic;");
                    sb.AppendLine($"using System.Data;");
                    sb.AppendLine($"using System.Linq;");
                    sb.AppendLine($"using System.Linq.Expressions;");
                    sb.AppendLine($"using System.Text;");
                    sb.AppendLine($"using System.Threading.Tasks;");
                    sb.AppendLine($"");

                    #endregion

                    #region 命名空间

                    sb.AppendLine($"namespace {baseClassSpace}Service");
                    sb.AppendLine($"{{");

                    #endregion

                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {baseTableDesc}业务逻辑层");
                    sb.AppendLine($"{tabOne}/// </summary>");
                    sb.AppendLine($"{tabOne}public class {className} : BaseService, {interfaceName}");
                    sb.AppendLine($"{tabOne}{{");

                    sb.AppendLine($"{tabTwo}#region 构造函数");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}/// <summary>");
                    sb.AppendLine($"{tabTwo}/// 文件日志初始化");
                    sb.AppendLine($"{tabTwo}/// </summary>");
                    sb.AppendLine($"{tabTwo}readonly ILogger<{className}> _logger;");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}/// <summary>");
                    sb.AppendLine($"{tabTwo}/// 构造函数");
                    sb.AppendLine($"{tabTwo}/// </summary>");
                    sb.AppendLine($"{tabTwo}public {className}(ILogger<{className}> logger, DbContext context) : base(context)");
                    sb.AppendLine($"{tabTwo}{{");
                    sb.AppendLine($"{tabTre}this._logger = logger;");
                    sb.AppendLine($"{tabTwo}}}");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}#endregion");

                    sb.AppendLine($"");
                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine($"}}");

                    File.WriteAllText(serviceFilePath, sb.ToString());

                    #endregion

                    #region 业务逻辑层接口输出

                    sb = new StringBuilder();

                    #region 引用文件

                    sb.AppendLine($"using {baseClassSpace}Common;");
                    sb.AppendLine($"using {baseClassSpace}Model.Models;");
                    sb.AppendLine($"using {baseClassSpace}Model.Dtos;");
                    sb.AppendLine($"using {baseClassSpace}Model.Extensions;");
                    sb.AppendLine($"using Microsoft.Data.SqlClient;");
                    sb.AppendLine($"using System;");
                    sb.AppendLine($"using System.Collections.Generic;");
                    sb.AppendLine($"using System.Linq;");
                    sb.AppendLine($"using System.Linq.Expressions;");
                    sb.AppendLine($"using System.Text;");
                    sb.AppendLine($"using System.Threading.Tasks;");
                    sb.AppendLine($"");

                    #endregion

                    #region 命名空间           

                    sb.AppendLine($"namespace {baseInterfaceSpace}Service");
                    sb.AppendLine($"{{");

                    #endregion

                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {baseTableDesc}业务逻辑接口层");
                    sb.AppendLine($"{tabOne}/// </summary>");
                    sb.AppendLine($"{tabOne}public interface {interfaceName} : IBaseService");
                    sb.AppendLine($"{tabOne}{{");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine($"}}");

                    File.WriteAllText(interfaceFilePath, sb.ToString());

                    #endregion
                }

                #region ServiceIOC

                File.WriteAllText(iocFilePath, iocSb.ToString());

                #endregion

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"4）生成业务逻辑层CS代码输出错误", ex);
                throw;
            }
        }

        #endregion

        #region 5）生成数据访问层CS代码

        /// <summary>
        /// 开始创建生成数据访问层代码CS文件
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        private void CreateDalFile(string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            string repositoryPath = $"{selectPath}\\Repository\\";
            string interfacePath = $"{selectPath}\\IRepository\\";

            string filePath = $"{selectPath}\\Dal\\";
            FileHelper.FilePathCheck(filePath);

            var classSpaceName = txtSpaceName.Text.Trim();
            //string[] classArr = classSpaceName.Split('.');
            //var baseArr = classArr.Take(classArr.Count() - 1).ToArray();string.Join(".", baseArr)
            var baseClassSpace = classSpaceName + ".";
            var baseInterfaceSpace = baseClassSpace + "I";

            var className = string.Empty;
            var interfaceName = string.Empty;

            foreach (var table in tableList)
            {
                var tableName = table.Name; // 表名
                if (table.Comment == null) continue;
                var tableDesc = table.Comment.Replace(":", "："); // 表描述
                var shortTableDesc = tableDesc.Split('：')[0]; // 表基本描述【描述中冒号前面的部分】


                className = GetClassName(tableName);
                interfaceName = "I" + className;

                //iocSb.AppendLine($"services.AddTransient<{interfaceName}Service, {className}Service>(); // {baseTableDesc}");

                var serviceFilePath = $"{repositoryPath}{className}Repository.cs";
                var interfaceFilePath = $"{interfacePath}{interfaceName}Repository.cs";

                StringBuilder sb = new StringBuilder();
                //filePath = $"{selectPath}\\Dal\\{tableName}Dal.cs";

                if (shortTableDesc == tableName)
                {
                    shortTableDesc = $"{{{shortTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                }

                #region 数据仓储层输出

                #region 开发引用命名空间

                sb.AppendLine($"using System;");
                sb.AppendLine($"using System.Data;");
                sb.AppendLine($"using System.Data.SqlClient;");
                sb.AppendLine($"using System.Collections.Generic;");
                sb.AppendLine($"using {baseClassSpace}IRepository;");
                sb.AppendLine($"using {baseClassSpace}Common;");
                sb.AppendLine($"using {baseClassSpace}Model.Models;");
                sb.AppendLine($"using {baseClassSpace}Model.Dtos;");
                sb.AppendLine($"using {baseClassSpace}Model.Extensions;");
                sb.AppendLine($"");

                #endregion

                sb.AppendLine($"namespace {baseClassSpace}Repository");
                sb.AppendLine($"{{");
                sb.AppendLine($"{tabOne}/// <summary>");
                sb.AppendLine($"{tabOne}/// {shortTableDesc}数据访问层");
                sb.AppendLine($"{tabOne}/// </summary>");
                sb.AppendLine($"{tabOne}public class {tableName}Dal : SqlServerHelper, I{tableName}Dal, IDbHelper");
                sb.AppendLine($"{tabOne}{{");
                sb.AppendLine($"{tabTwo}internal string ConnectionString = SqlHelper.ConnectionStringEducation;");
                sb.AppendLine($"{tabTwo}public {tableName}Dal()");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}base.connectionString = ConnectionString;");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#region 获取{shortTableDesc}分页数据");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}/// <summary>");
                sb.AppendLine($"{tabTwo}/// 获取{shortTableDesc}分页数据");
                sb.AppendLine($"{tabTwo}/// </summary>");
                sb.AppendLine($"{tabTwo}/// <param name=\"paramList\">分页参数</param>");
                sb.AppendLine($"{tabTwo}/// <returns></returns>");
                sb.AppendLine($"{tabTwo}public override DataTable PageData(Dictionary<string, string> paramList)");
                sb.AppendLine($"{tabTwo}{{");
                sb.AppendLine($"{tabTre}#region 分页参数处理");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTre}var pagger = GetPagingParameters(paramList);");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTre}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTre}string strQry = \"\";");
                sb.AppendLine($"{tabTre}var strName = paramList.ContainsKey(\"Name\") ? (paramList[\"Name\"] ?? \"\") : \"\";");
                sb.AppendLine($"{tabTre}if (!string.IsNullOrEmpty(strName))");
                sb.AppendLine($"{tabTre}{{");
                sb.AppendLine($"{tabTre}    //strQry = string.Format(@\" AND (F_Name LIKE '%{{0}}%')\", strName);");
                sb.AppendLine($"{tabTre}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTre}string strSql = string.Format(@\"");
                sb.AppendLine($"	        ;WITH PageTb AS (");
                sb.AppendLine($"		        SELECT ROW_NUMBER() OVER (ORDER BY F_CreateTime DESC) RowNumber, ");
                sb.AppendLine($"			        *");
                sb.AppendLine($"		        FROM dbo.[{tableName}] WHERE (1 = 1) {{2}} )");
                sb.AppendLine($"	        SELECT * ");
                sb.AppendLine($"	        FROM PageTb a");
                sb.AppendLine($"	        CROSS JOIN (SELECT MAX(RowNumber) AS RecordCount FROM PageTb) AS b ");
                sb.AppendLine($"	        WHERE (a.RowNumber BETWEEN {{0}} AND {{1}});");
                sb.AppendLine($"	        \", pagger.Min, pagger.Max, strQry);");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTre}return SqlHelper.GetDataTable(strSql, connectionString);");
                sb.AppendLine($"{tabTwo}}}");
                sb.AppendLine($"");
                sb.AppendLine($"{tabTwo}#endregion");
                sb.AppendLine($"");
                sb.AppendLine($"{tabOne}}}");
                sb.AppendLine($"}}");
                sb.AppendLine($"");

                File.WriteAllText(filePath, sb.ToString());

                #endregion

                #region 数据仓储层接口输出

                #region 开发引用命名空间

                sb.AppendLine($"using System;");
                sb.AppendLine($"using System.Data;");
                sb.AppendLine($"using System.Data.SqlClient;");
                sb.AppendLine($"using System.Collections.Generic;");
                sb.AppendLine($"using {baseClassSpace}Common;");
                sb.AppendLine($"using {baseClassSpace}Model.Models;");
                sb.AppendLine($"using {baseClassSpace}Model.Dtos;");
                sb.AppendLine($"using {baseClassSpace}Model.Extensions;");
                sb.AppendLine($"");

                #endregion



                #endregion
            }
        }

        /// <summary>
        /// 开始创建生成数据访问层代码CS文件
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        private void CreateRepositoryFile(string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            try
            {

                string repositoryPath = $"{selectPath}\\Repository\\";
                string interfacePath = $"{selectPath}\\IRepository\\";

                FileHelper.FilePathCheck(repositoryPath);
                FileHelper.FilePathCheck(interfacePath);

                var classSpaceName = txtSpaceName.Text.Trim();
                //string[] classArr = classSpaceName.Split('.');
                //var baseArr = classArr.Take(classArr.Count() - 1).ToArray();string.Join(".", baseArr)
                var baseClassSpace = classSpaceName + ".";
                var baseInterfaceSpace = baseClassSpace + "I";

                var className = string.Empty;
                var interfaceName = string.Empty;
                StringBuilder sb = new StringBuilder();

                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 表名
                    if (table.Comment == null) continue;
                    var tableDesc = table.Comment.Replace(":", "："); // 表描述
                    var shortTableDesc = tableDesc.Split('：')[0]; // 表基本描述【描述中冒号前面的部分】

                    className = GetClassName(tableName);
                    interfaceName = "I" + className;
                    className += "Repository";
                    interfaceName += "Repository";

                    //iocSb.AppendLine($"services.AddTransient<{interfaceName}Service, {className}Service>(); // {baseTableDesc}");

                    var serviceFilePath = $"{repositoryPath}{className}.cs";
                    var interfaceFilePath = $"{interfacePath}{interfaceName}.cs";

                    if (shortTableDesc == tableName)
                    {
                        shortTableDesc = $"{{{shortTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                    }

                    #region 数据仓储层输出

                    sb = new StringBuilder();

                    #region 开发引用命名空间

                    sb.AppendLine($"using System;");
                    sb.AppendLine($"using System.Data;");
                    sb.AppendLine($"using System.Data.SqlClient;");
                    sb.AppendLine($"using System.Collections.Generic;");
                    sb.AppendLine($"using {baseClassSpace}IRepository;");
                    sb.AppendLine($"using {baseClassSpace}Common;");
                    sb.AppendLine($"using {baseClassSpace}Model.Models;");
                    sb.AppendLine($"using {baseClassSpace}Model.Dtos;");
                    sb.AppendLine($"using {baseClassSpace}Model.Extensions;");
                    sb.AppendLine($"");

                    #endregion

                    #region 内容输出

                    sb.AppendLine($"namespace {baseClassSpace}Repository");
                    sb.AppendLine($"{{");
                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {shortTableDesc}数据仓储层");
                    sb.AppendLine($"{tabOne}/// </summary>");
                    sb.AppendLine($"{tabOne}public class {className} : {interfaceName}");
                    sb.AppendLine($"{tabOne}{{");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}public {className}()");
                    sb.AppendLine($"{tabTwo}{{");
                    sb.AppendLine($"{tabTre}");
                    sb.AppendLine($"{tabTwo}}}");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTwo}#region 获取{shortTableDesc}分页数据");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTwo}/// <summary>");
                    sb.AppendLine($"{tabTwo}/// 获取{shortTableDesc}分页数据");
                    sb.AppendLine($"{tabTwo}/// </summary>");
                    sb.AppendLine($"{tabTwo}/// <param name=\"paramList\">分页参数</param>");
                    sb.AppendLine($"{tabTwo}/// <returns></returns>");
                    sb.AppendLine($"{tabTwo}public override DataTable PageData(Dictionary<string, string> paramList)");
                    sb.AppendLine($"{tabTwo}{{");
                    sb.AppendLine($"{tabTre}#region 分页参数处理");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTre}var pagger = GetPagingParameters(paramList);");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTre}#endregion");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTre}string strQry = \"\";");
                    sb.AppendLine($"{tabTre}var strName = paramList.ContainsKey(\"Name\") ? (paramList[\"Name\"] ?? \"\") : \"\";");
                    sb.AppendLine($"{tabTre}if (!string.IsNullOrEmpty(strName))");
                    sb.AppendLine($"{tabTre}{{");
                    sb.AppendLine($"{tabTre}    //strQry = string.Format(@\" AND (F_Name LIKE '%{{0}}%')\", strName);");
                    sb.AppendLine($"{tabTre}}}");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTre}string strSql = string.Format(@\"");
                    sb.AppendLine($"	        ;WITH PageTb AS (");
                    sb.AppendLine($"		        SELECT ROW_NUMBER() OVER (ORDER BY F_CreateTime DESC) RowNumber, ");
                    sb.AppendLine($"			        *");
                    sb.AppendLine($"		        FROM dbo.[{tableName}] WHERE (1 = 1) {{2}} )");
                    sb.AppendLine($"	        SELECT * ");
                    sb.AppendLine($"	        FROM PageTb a");
                    sb.AppendLine($"	        CROSS JOIN (SELECT MAX(RowNumber) AS RecordCount FROM PageTb) AS b ");
                    sb.AppendLine($"	        WHERE (a.RowNumber BETWEEN {{0}} AND {{1}});");
                    sb.AppendLine($"	        \", pagger.Min, pagger.Max, strQry);");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTre}return SqlHelper.GetDataTable(strSql, connectionString);");
                    sb.AppendLine($"{tabTwo}}}");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabTwo}#endregion");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine($"}}");
                    sb.AppendLine($"");

                    #endregion

                    File.WriteAllText(serviceFilePath, sb.ToString());

                    #endregion

                    #region 数据仓储层接口输出

                    sb = new StringBuilder();

                    #region 开发引用命名空间

                    sb.AppendLine($"using System;");
                    sb.AppendLine($"using System.Data;");
                    sb.AppendLine($"using System.Data.SqlClient;");
                    sb.AppendLine($"using System.Collections.Generic;");
                    sb.AppendLine($"using {baseClassSpace}Common;");
                    sb.AppendLine($"using {baseClassSpace}Model.Models;");
                    sb.AppendLine($"using {baseClassSpace}Model.Dtos;");
                    sb.AppendLine($"using {baseClassSpace}Model.Extensions;");
                    sb.AppendLine($"");

                    #endregion

                    #region 内容输出

                    sb.AppendLine($"namespace {baseInterfaceSpace}Repository");
                    sb.AppendLine($"{{");
                    sb.AppendLine($"{tabOne}/// <summary>");
                    sb.AppendLine($"{tabOne}/// {shortTableDesc}数据仓储层接口");
                    sb.AppendLine($"{tabOne}/// </summary>");
                    sb.AppendLine($"{tabOne}public class {interfaceName}");
                    sb.AppendLine($"{tabOne}{{");
                    sb.AppendLine($"{tabTwo}");
                    sb.AppendLine($"{tabTwo}public {interfaceName}()");
                    sb.AppendLine($"{tabTwo}{{");
                    sb.AppendLine($"{tabTre}");
                    sb.AppendLine($"{tabTwo}}}");
                    sb.AppendLine($"");
                    sb.AppendLine($"");
                    sb.AppendLine($"{tabOne}}}");
                    sb.AppendLine($"}}");
                    sb.AppendLine($"");

                    #endregion

                    File.WriteAllText(interfaceFilePath, sb.ToString());

                    #endregion
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"5）生成数据访问层CS代码输出错误", ex);
                throw;
            }
        }

        #endregion

        #region 6）生成前端资源文件

        /// <summary>
        /// 开始创建生成表示层Table或者TreeView Html文件
        /// </summary>
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        private void CreateViewResourcesFile(string selectPath, List<Tables> tableList, List<Columns> columnList)
        {
            #region 命名空间检查

            //var websiteSpaceName = this.txtSpaceName.Text.Trim();

            //if (string.IsNullOrEmpty(websiteSpaceName))
            //{
            //    MessageBox.Show("控制器所在站点命名空间为空！");
            //    return;
            //}

            //var rootSpaceName = this.txtSpaceName.Text.Trim();
            //if (string.IsNullOrEmpty(rootSpaceName))
            //{
            //    MessageBox.Show("根命名空间为空！");
            //    return;
            //}

            //var modelSpaceName = $"{rootSpaceName}.Model.Models"; // 实体文件命名空间
            //var dtoSpaceName = $"{rootSpaceName}.Model.Dtos"; // 实体文件命名空间
            //var areaRootSpaceName = $"{rootSpaceName}.Web.Areas"; // 资源根命名空间

            //var enableLogging = RefMaterial?.EnableLogging;
            //var enableCaching = RefMaterial?.EnableCaching;
            //var efContext = RefMaterial?.EfContext;

            #endregion

            #region 检查资源根目录

            var resourceRootPath = $"{selectPath}\\view-resources\\"; // 资源根目录

            FileHelper.FilePathCheck(resourceRootPath);

            #endregion

            try
            {
                #region 资源名称汇总

                Dictionary<string, string> areaList = new();

                foreach (var table in tableList)
                {
                    var s = table.Name.Split('_')[0];

                    if (!areaList.ContainsKey(s))
                    {
                        areaList.Add(s, s);
                    }
                }

                #endregion

                StringBuilder sb = new();

                foreach (KeyValuePair<string, string> keyValue in areaList)
                {
                    #region 检查资源及子目录

                    var title = keyValue.Value;
                    var resourceName = title.ToUpperFirst(); // 资源名称
                    var resourcePath = Path.Combine($"{resourceRootPath}", $"{resourceName}\\");

                    FileHelper.FilePathCheck(resourcePath);

                    var viewsPath = Path.Combine($"{resourcePath}", $"");
                    FileHelper.FilePathCheck(viewsPath);

                    string jsPath = string.Empty, cssPath = string.Empty;

                    #endregion

                    // 表列项数据
                    var tables = tableList.Where(entity => entity.Name.StartsWith(title)).ToList();

                    foreach (var table in tables)
                    {
                        var tableName = table.Name; // 表名
                        if (table.Comment == null) continue;
                        var tableDesc = table.Comment.Replace(":", "："); // 表描述
                        //var tableViewName = tableName.ToSingularModelName(); // 表实体名称
                        //if (isSingularEntity) tableViewName = tableViewName;
                        var tableModelName = tableName.ToSingularModelName(); // 表实体名称
                        var controllerName = GetControllerName(tableName);
                        controllerName = controllerName.Replace(resourceName, ""); // 控制器名去掉前面的去域名
                        var tableViewModelName = tableModelName + "ViewModel"; // 表ViewModel对象
                        var lowerTableName = tableModelName.ToLower(); // 小写表名
                        var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】

                        jsPath = $"{viewsPath}\\{controllerName}\\TableList.js";
                        cssPath = $"{viewsPath}\\{controllerName}\\TableList.css";

                        FileHelper.FilePathCheck(jsPath);

                        if (baseTableDesc == tableName)
                        {
                            baseTableDesc = $"{{{baseTableDesc}}}"; // 如果表没有添加中文注释，此方法方便替换
                        }

                        var primaryKey = "Id"; // 主键
                                               //var primaryKeyType = "uniqueidentifier"; // Guid类型
                        var primaryKeyObjectName = primaryKey;
                        //var primaryKeyObjectDesc = "";

                        //var dateInput = false; // 是否有日期输入字段

                        var tableColumn = columnList.Where(entity => entity.TableName == tableName).ToList();
                        var columnLength = tableColumn.Count;

                        var isTree = IsTree(tableColumn); // 是否树结构表
                        if (isTree)
                        {
                            jsPath = $"{viewsPath}\\{controllerName}\\TreeList.js";
                            cssPath = $"{viewsPath}\\{controllerName}\\TableList.css";
                        }
                        sb = new StringBuilder();

                        sb.AppendLine($"/**");
                        sb.AppendLine($" * {baseTableDesc}");
                        sb.AppendLine($" * */");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabOne}");
                        sb.AppendLine($"{tabTwo}let $table = $('#{lowerTableName}-table'),");
                        sb.AppendLine($"{tabTre}$remove = $('#remove'),");
                        sb.AppendLine($"{tabTre}selections = [],");
                        sb.AppendLine($"{tabTre}key = '{primaryKey}';");
                        sb.AppendLine($"{tabTwo}");

                        sb.AppendLine($"{tabTwo}let pageNumber = 1, pageSize = 10;"); // , width = 0
                        sb.AppendLine($"{tabTwo}let pageListUrl = \"/{resourceName}/{controllerName}/PageList\";");
                        sb.AppendLine($"{tabTwo}");
                        sb.AppendLine($"{tabTwo}$(function () {{");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}$table = $('#{lowerTableName}-table'),");
                        sb.AppendLine($"{tabTre}    $remove = $('#remove');");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}$(\"#btnAdd\").off('click').on('click', function () {{");

                        foreach (var column in tableColumn)
                        {
                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment; // 列描述

                            if (column.IsPK == 1 && column.DataType == "int")
                            {
                                sb.AppendLine($"{tabTre}    $(\"#{columnName}\").val(\"0\"); // {columnDesc}");
                            }
                        }

                        //sb.AppendLine($"{tabTre}    $(\"#Name\").focus();");

                        sb.AppendLine($"{tabTre}    $(\"#editModelLabel\").html(\"{baseTableDesc}信息添加\");");
                        sb.AppendLine($"{tabTre}    $('#editModel').modal('toggle');");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}initTable();");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}$table.find(\"thead\").addClass(\"thead-dark\");");
                        sb.AppendLine($"");
                        if (isTree)
                        {
                            sb.AppendLine($"{tabTre}getTreeView();");
                        }
                        sb.AppendLine($"{tabTre}// 关键词查询");
                        sb.AppendLine($"{tabTre}$('input[name=\"search\"]').off('keydown').on('keydown', function (e) {{");
                        sb.AppendLine($"{tabTre}    if (e.code == \"Enter\") {{");
                        sb.AppendLine($"{tabTre}        pageNumber = 1;");
                        sb.AppendLine($"{tabTre}        refreshTable();");
                        sb.AppendLine($"{tabTre}    }}");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"{tabTre}");

                        sb.AppendLine($"            // 搜索");
                        sb.AppendLine($"            $('#btnSearch').off('click').on('click', function () {{");
                        sb.AppendLine($"                pageNumber = 1;");
                        sb.AppendLine($"                refreshTable();");
                        sb.AppendLine($"            }});");
                        sb.AppendLine($"");

                        sb.AppendLine($"             // 清空查询条件");
                        sb.AppendLine($"             $('#btnClear').off('click').on('click', function () {{");
                        sb.AppendLine($"                 $('#toolbar form')[0].reset();");
                        sb.AppendLine($"                 pageNumber = 1;");
                        sb.AppendLine($"                 refreshTable();");
                        sb.AppendLine($"             }});");
                        sb.AppendLine($"");

                        if (isTree)
                        {
                            sb.AppendLine($"    // 根菜单");
                            sb.AppendLine($"    $(\"#btnRoot\").off(\"click\").on(\"click\", function () {{");
                            sb.AppendLine($"        $(\"#ParentId\").val(0);");
                            sb.AppendLine($"        CheckParentName();");
                            sb.AppendLine($"        pageNumber = 1;");
                            sb.AppendLine($"        refreshTable();");
                            sb.AppendLine($"    }});");
                            sb.AppendLine($"");
                        }

                        //sb.AppendLine($"{tabTre}// 填充随机数据");
                        //sb.AppendLine($"{tabTre}$(\"#btnRandomData\").off('click').on('click', function () {{");
                        //sb.AppendLine($"{tabTre}    CTD.Modal.CircleMessage(circleModalId, \"数据填充操作正在进行中，请稍候...\");");
                        //sb.AppendLine($"{tabTre}    $(\"#\" + circleModalId).modal(\"toggle\");");
                        //sb.AppendLine($"{tabTre}    $.ajax({{");
                        //sb.AppendLine($"{tabTre}        url: '/{areaName}/{controllerName}/SqlBulkRandomData/?rnd=' + (Math.random() * 10),");
                        //sb.AppendLine($"{tabTre}        type: 'GET',");
                        //sb.AppendLine($"{tabTre}        data: {{ rnd: (Math.random() * 16) }},");
                        //sb.AppendLine($"{tabTre}        success: function (rst) {{");
                        //sb.AppendLine($"{tabTre}            $(\"#\" + circleModalId).modal(\"hide\");");
                        //sb.AppendLine($"{tabTre}            if (rst && rst.success) {{");
                        //sb.AppendLine($"{tabTre}                refreshTable();");
                        //sb.AppendLine($"{tabTre}                $.alert({{ title: '操作成功!', content: rst.message }});");
                        //sb.AppendLine($"{tabTre}            }} else {{");
                        //sb.AppendLine($"{tabTre}                modals.error(rst.message ?? rst.Message);");
                        //sb.AppendLine($"{tabTre}            }}");
                        //sb.AppendLine($"{tabTre}        }}");
                        //sb.AppendLine($"{tabTre}    }});");
                        //sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"{tabTwo}}});");
                        sb.AppendLine($"{tabTwo}");

                        if (isTree)
                        {
                            sb.AppendLine($"        function getTreeView() {{");
                            sb.AppendLine($"            let url = \"/{resourceName}/{controllerName}/TreeData/?id=&selectId=\";");
                            sb.AppendLine($"            $.get(url + \"&rnd=\" + (Math.random() * 10), function (rst) {{");
                            sb.AppendLine($"                //console.log(rst);");
                            sb.AppendLine($"                //console.log(rst.Data);");
                            sb.AppendLine($"                if (rst && rst.success) {{");
                            sb.AppendLine($"");
                            sb.AppendLine($"                    $('#tree').bstreeview({{");
                            sb.AppendLine($"                        data: rst.Data,");
                            sb.AppendLine($"                        expandIcon: 'fa fa-angle-down fa-fw',");
                            sb.AppendLine($"                        collapseIcon: 'fa fa-angle-right fa-fw',");
                            sb.AppendLine($"                        indent: 1.25,");
                            sb.AppendLine($"                        parentsMarginLeft: '1.25rem',");
                            sb.AppendLine($"                        openNodeLinkOnNewTab: true");
                            sb.AppendLine($"                    }});");
                            sb.AppendLine($"");
                            sb.AppendLine($"                    $(\".list-group-item\").on('click', function (e) {{");
                            sb.AppendLine($"                        let id = e.target.getAttribute('id');");
                            sb.AppendLine($"                        let text = $(e.target).text();");
                            sb.AppendLine($"                        if (id == null) id = 0;");
                            sb.AppendLine($"                        if (id.length > 0) {{");
                            sb.AppendLine($"                            $(\"#Pid\").val(id);");
                            sb.AppendLine($"                            $(\"#PName\").val(text);");
                            sb.AppendLine($"                            $(\"#ParentId\").val(id);");
                            sb.AppendLine($"                            $(\"#ParentName\").val(text);");
                            sb.AppendLine($"                            pageNumber = 1;");
                            sb.AppendLine($"                            refreshTable();");
                            sb.AppendLine($"                        }}");
                            sb.AppendLine($"                    }});");
                            sb.AppendLine($"");
                            sb.AppendLine($"                }} else {{");
                            sb.AppendLine($"                    modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"                }}");
                            sb.AppendLine($"            }});");
                            sb.AppendLine($"        }}");

                            sb.AppendLine($"");
                            sb.AppendLine($"function CheckParentName() {{");
                            sb.AppendLine($"    var title = $(\"input[name='search']\").val();");
                            sb.AppendLine($"    if (title == undefined || title.length == 0) {{");
                            sb.AppendLine($"        $table.bootstrapTable('hideColumn', 'PName');");
                            sb.AppendLine($"    }} else {{");
                            sb.AppendLine($"        $table.bootstrapTable('showColumn', 'PName');");
                            sb.AppendLine($"    }}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"function ParentSelect() {{");
                            sb.AppendLine($"    $('#ParentMenuModal').modal('show');");
                            sb.AppendLine($"    // 放到表初始化之后");
                            sb.AppendLine($"    getSelectTreeView();");
                            sb.AppendLine($"    $(\"#authMenus-table thead\").addClass(\"thead-dark\");");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"function getSelectTreeView() {{");
                            sb.AppendLine($"    var url = \"/{resourceName}/{controllerName}/TreeData\";");
                            sb.AppendLine($"    $.get(url + \"?rnd=\" + (Math.random() * 10), function (rst) {{");
                            sb.AppendLine($"        //console.log(rst);");
                            sb.AppendLine($"        //console.log(rst.Data);");
                            sb.AppendLine($"        //$(\"#\" + circleModalId).modal(\"hide\");");
                            sb.AppendLine($"        if (rst && rst.success) {{");
                            sb.AppendLine($"");
                            sb.AppendLine($"            $('#selecttree').bstreeview({{");
                            sb.AppendLine($"                data: rst.Data,");
                            sb.AppendLine($"                expandIcon: 'fa fa-angle-down fa-fw',");
                            sb.AppendLine($"                collapseIcon: 'fa fa-angle-right fa-fw',");
                            sb.AppendLine($"                indent: 1.25,");
                            sb.AppendLine($"                parentsMarginLeft: '1.25rem',");
                            sb.AppendLine($"                openNodeLinkOnNewTab: true");
                            sb.AppendLine($"            }});");
                            sb.AppendLine($"            // $(\"#selecttree .list-group-item\")");
                            sb.AppendLine($"");
                            sb.AppendLine($"            $(\"#selecttree .list-group-item\").on('click', function (e) {{");
                            sb.AppendLine($"                //debugger;");
                            sb.AppendLine($"                //var parent = e.target.parentElement;");
                            sb.AppendLine($"                //var ParentId = parent == undefined ? \"\" : parent.getAttribute('id');");
                            sb.AppendLine($"                //alert(\"Id:\" + e.target.getAttribute('id') + \" * \" + \"PId:\" + parent.getAttribute('id'));");
                            sb.AppendLine($"                var id = e.target.getAttribute('id');");
                            sb.AppendLine($"                var text = $(e.target).text();");
                            sb.AppendLine($"                var txtId = $(\"#Id\").val();");
                            sb.AppendLine($"");
                            sb.AppendLine($"                if (id) {{");
                            sb.AppendLine($"                    if (id == txtId) {{");
                            sb.AppendLine($"                        modals.error(\"请选择正确的父级菜单！\");");
                            sb.AppendLine($"                        return;");
                            sb.AppendLine($"                    }}");
                            sb.AppendLine($"");
                            sb.AppendLine($"                    $(\"#Pid\").val(id);");
                            sb.AppendLine($"                    $(\"#PName\").val(text);");
                            sb.AppendLine($"                    $(\"#ParentId\").val(id);");
                            sb.AppendLine($"                    $(\"#ParentName\").val(text);");
                            sb.AppendLine($"");
                            sb.AppendLine($"                    $('#ParentMenuModal').modal('hide'); // 隐藏弹出框");
                            sb.AppendLine($"                }}");
                            sb.AppendLine($"            }});");
                            sb.AppendLine($"");
                            sb.AppendLine($"            //return rst.data;");
                            sb.AppendLine($"            //$.alert({{ title: '操作提示!', content: \"成功\" }});");
                            sb.AppendLine($"        }} else {{");
                            sb.AppendLine($"            modals.error(rst.Message);");
                            sb.AppendLine($"        }}");
                            sb.AppendLine($"    }});");
                            sb.AppendLine($"");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");

                        }

                        sb.AppendLine($"{tabTwo}// 刷新表格数据");
                        sb.AppendLine($"{tabTwo}function refreshTable() {{");
                        //sb.AppendLine($"{tabTre}$table.bootstrapTable({{ url: pageListUrl }});");
                        sb.AppendLine($"{tabTre}$table.bootstrapTable('refresh', {{ pageNumber: pageNumber, pageSize: pageSize }});");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"{tabTwo}");
                        sb.AppendLine($"{tabTwo}// 初始化表");
                        sb.AppendLine($"{tabTwo}function initTable() {{");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}//先销毁表格");
                        sb.AppendLine($"{tabTre}$table.bootstrapTable('destroy');");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}$table.bootstrapTable({{");
                        sb.AppendLine($"{tabTre}    height: getHeight(),");
                        sb.AppendLine($"{tabTre}    method: 'get', // 请求方式（*）");
                        sb.AppendLine($"{tabTre}    dataType: \"json\", // 数据类型");
                        sb.AppendLine($"{tabTre}    url: pageListUrl, // 请求后台地址,");
                        sb.AppendLine($"{tabTre}    toolbar: '#toolbar', //工具按钮用哪个容器");
                        sb.AppendLine($"{tabTre}    theadClasses: 'thead-dark', // 表头样式");
                        sb.AppendLine($"{tabTre}    striped: true, // 使表格带有条纹");
                        sb.AppendLine($"{tabTre}    uniqueId: key, // 唯一标识");
                        sb.AppendLine($"{tabTre}    idField: key, // 标识哪个字段为id主键");
                        sb.AppendLine($"{tabTre}    pagination: true, // 在表格底部显示分页工具栏");
                        sb.AppendLine($"{tabTre}    pageSize: pageSize, // 分页大小");
                        sb.AppendLine($"{tabTre}    pageNumber: pageNumber, // 当前页码");
                        sb.AppendLine($"{tabTre}    pageList: [10, 20, 50, 100, 200, 500],");
                        sb.AppendLine($"{tabTre}    sidePagination: \"server\", //表格分页的位置");
                        sb.AppendLine($"{tabTre}    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder");
                        sb.AppendLine($"{tabTre}    //设置为limit可以获取limit, offset, search, sort, order");
                        sb.AppendLine($"{tabTre}    queryParamsType: \"undefined\",");
                        sb.AppendLine($"{tabTre}    queryParams: function queryParams(params) {{ //设置查询参数");
                        sb.AppendLine($"{tabTre}        var param = {{");
                        sb.AppendLine($"{tabTre}            pageNumber: params.pageNumber,");
                        sb.AppendLine($"{tabTre}            pageSize: params.pageSize,");

                        if (isTree)
                        {
                            sb.AppendLine($"{tabTre}            id: $(\"#Pid\").val(),");
                        }

                        sb.AppendLine($"{tabTre}            title: $(\"input[name='search']\").val()");

                        if (columnLength > 10)
                        {
                            sb.AppendLine($"{tabTre}            ,startDate: $(\"input[name='startDate']\").val()");
                            sb.AppendLine($"{tabTre}            ,endDate: $(\"input[name='endDate']\").val()");
                        }

                        sb.AppendLine($"{tabTre}        }};");
                        sb.AppendLine($"{tabTre}        pageNumber = params.pageNumber;");
                        sb.AppendLine($"{tabTre}        return param;");
                        sb.AppendLine($"{tabTre}    }},");
                        sb.AppendLine($"{tabTre}    columns: [");
                        sb.AppendLine($"{tabTre}        [");
                        sb.AppendLine($"{tabTre}            {{");
                        sb.AppendLine($"{tabTre}                field: 'checked',");
                        sb.AppendLine($"{tabTre}                checkbox: true");
                        sb.AppendLine($"{tabTre}            }}, {{");
                        sb.AppendLine($"{tabTre}                title: '序号',");
                        sb.AppendLine($"{tabTre}                field: 'RowNumber',");
                        sb.AppendLine($"{tabTre}                width: 60,");
                        sb.AppendLine($"{tabTre}                align: 'center',");
                        sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                        sb.AppendLine($"{tabTre}                	var options = $table.bootstrapTable('getOptions');");
                        sb.AppendLine($"{tabTre}                	return options.pageSize * (options.pageNumber - 1) + index + 1;");
                        sb.AppendLine($"{tabTre}                }}");
                        sb.AppendLine($"{tabTre}            }}, {{");
                        sb.AppendLine($"{tabTre}                title: '操作',");
                        sb.AppendLine($"{tabTre}                width: 90,");
                        sb.AppendLine($"{tabTre}                halign: 'center',");
                        sb.AppendLine($"{tabTre}                align: 'center',");
                        sb.AppendLine($"{tabTre}                events: operateEvents,");
                        sb.AppendLine($"{tabTre}                formatter: operateFormatter");



                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】                   

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            if (NoHandlerColumn(column))
                            {
                                // 去除字段
                            }
                            else
                            {
                                var rightTwoLetter = columnName.Length > 2 ? columnName.Substring(columnName.Length - 2, 2).ToLower() : columnName.ToLower();

                                if (rightTwoLetter == "id")
                                {
                                    // 尾部2个字符为ID的不显示
                                    // 父级名称
                                    if (columnName.ToLower() == "pid")
                                    {
                                        sb.AppendLine($"{tabTre}            }}, {{");
                                        sb.AppendLine($"{tabTre}                field: 'PName',");
                                        sb.AppendLine($"{tabTre}                title: '父级单元',");
                                        sb.AppendLine($"{tabTre}                width: 120,");
                                        sb.AppendLine($"{tabTre}                halign: 'center',");
                                        sb.AppendLine($"{tabTre}                align: 'center',");
                                        sb.AppendLine($"{tabTre}                formatter: tipsFormatter");
                                    }
                                }
                                else
                                {

                                    sb.AppendLine($"{tabTre}            }}, {{");
                                    sb.AppendLine($"{tabTre}                field: '{columnName}',");
                                    sb.AppendLine($"{tabTre}                title: '{baseColumnDesc}',");

                                    var tdWidth = 60; // 普通列宽带
                                    if (column.DataType == "datetime")
                                    {
                                        tdWidth = 105; // 日期列宽带
                                    }
                                    else
                                    {
                                        if (column.Length > 0)
                                        {
                                            tdWidth = 120;
                                        }
                                    }

                                    sb.AppendLine($"{tabTre}                width: {tdWidth},");
                                    sb.AppendLine($"{tabTre}                halign: 'center',");

                                    var align = "center";
                                    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                                    {
                                        align = "right"; // 数值型
                                    }
                                    else if (column.Length > 0)
                                    {
                                        align = "left"; // 字符型
                                    }

                                    sb.AppendLine($"{tabTre}                align: '{align}',");

                                    var formatter = "";
                                    if (column.DataType!.ToLower().Contains("char") && column.Length > 50)
                                    {
                                        formatter = "tipsFormatter"; // 字符型
                                    }

                                    if (column.DataType == "datetime") // 日期时间列表格式
                                    {
                                        if (bootstrapVersion == 4)
                                        {
                                            sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                                            sb.AppendLine($"{tabTre}                    return (value == null || value.length == 0) ? \"\" : value.toDateTimeString();");
                                            sb.AppendLine($"{tabTre}                }}");
                                        }
                                    }
                                    else if (column.DataType == "date") // 日期列表格式
                                    {
                                        sb.AppendLine($"{tabTre}                formatter: function (value, row, index) {{");
                                        sb.AppendLine($"{tabTre}                    return (value == null || value.length == 0) ? \"\" : value.toDateString();");
                                        sb.AppendLine($"{tabTre}                }}");
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(formatter))
                                        {
                                            sb.AppendLine($"{tabTre}                formatter: {formatter}");
                                        }
                                    }
                                }
                            }
                        }

                        foreach (var column in tableColumn.Where(s => s.Name == "State"))
                        {
                            sb.AppendLine($"{tabTre}                field: 'State',");
                            sb.AppendLine($"{tabTre}                title: '状态',");
                            sb.AppendLine($"{tabTre}                width: 60,");
                            sb.AppendLine($"{tabTre}                halign: 'center',");
                            sb.AppendLine($"{tabTre}                align: 'center',");
                            sb.AppendLine($"{tabTre}                formatter: stateFormatter");
                            sb.AppendLine($"{tabTre}            }}, {{");
                        }


                        sb.AppendLine($"{tabTre}            }}");
                        sb.AppendLine($"{tabTre}        ]");
                        sb.AppendLine($"{tabTre}    ],");
                        sb.AppendLine($"{tabTre}    formatLoadingMessage: function () {{");
                        sb.AppendLine($"{tabTre}        return \"请稍等，正在加载中...\";");
                        sb.AppendLine($"{tabTre}    }},");
                        sb.AppendLine($"{tabTre}    formatNoMatches: function () {{ //没有匹配的结果");
                        sb.AppendLine($"{tabTre}        return '无符合条件的记录';");
                        sb.AppendLine($"{tabTre}    }}");
                        sb.AppendLine($"{tabTre}}});");
                        //sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}// sometimes footer render error.");
                        sb.AppendLine($"{tabTre}");
                        //sb.AppendLine($"{tabTre}$table.find(\"thead\").addClass(\"thead-dark\");");
                        //sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}setTimeout(function () {{");
                        sb.AppendLine($"{tabTre}    $table.bootstrapTable('resetView');");
                        sb.AppendLine($"{tabTre}    $('[data-toggle=\"tooltip\"]').tooltip();");
                        sb.AppendLine($"{tabTre}}}, 200);");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}$table.on('check.bs.table uncheck.bs.table ' +");
                        sb.AppendLine($"{tabTre}    'check-all.bs.table uncheck-all.bs.table', function () {{");
                        sb.AppendLine($"{tabTre}        $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}        // save your data, here just save the current page");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}        selections = getIdSelections();");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}        // push or splice the selections if you want to save all data selections");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}    }});");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}$remove.off('click').on('click', function () {{ // 批量删除");
                        sb.AppendLine($"{tabTre}    var ids = getIdSelections();");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"{tabTre}    $remove.prop('disabled', true);");
                            sb.AppendLine($"{tabTre}    BatchLogicalDelete(ids); // 批量逻辑删除");
                        }
                        else
                        {
                            //sb.AppendLine($"{tabTre}    $table.bootstrapTable('remove', {{");
                            //sb.AppendLine($"{tabTre}        field: key,");
                            //sb.AppendLine($"{tabTre}        values: ids");
                            //sb.AppendLine($"{tabTre}    }});");
                            sb.AppendLine($"{tabTre}    $remove.prop('disabled', true);");
                            sb.AppendLine($"{tabTre}    BatchDelete(ids.toString()); // 批量删除");
                        }

                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}$(window).resize(function () {{");
                        sb.AppendLine($"{tabTre}    $table.bootstrapTable('resetView', {{");
                        sb.AppendLine($"{tabTre}        height: getHeight()");
                        sb.AppendLine($"{tabTre}    }});");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTwo}// 获取选择项");
                        sb.AppendLine($"{tabTwo}function getIdSelections() {{");
                        sb.AppendLine($"{tabTre}return $.map($table.bootstrapTable('getSelections'), function (row) {{");
                        sb.AppendLine($"{tabTre}    return row[key];");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTwo}// 操作内容格式化");
                        sb.AppendLine($"{tabTwo}function operateFormatter(value, row, index) {{");
                        //sb.AppendLine($"{tabTre}return [");
                        //sb.AppendLine($"{tabTre}    '<a class=\"edit\" href=\"javascript:void(0)\" title=\"修改{shortTableDesc}\">',");
                        //sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-edit\"></i>',");
                        //sb.AppendLine($"{tabTre}    '</a>  ',");
                        //sb.AppendLine($"{tabTre}    '<a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{shortTableDesc}\">',");
                        //sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                        //sb.AppendLine($"{tabTre}    '</a>'");
                        //sb.AppendLine($"{tabTre}].join('');");
                        sb.AppendLine($"{tabTre}let edit = ['<a class=\"edit\" href=\"javascript:void(0)\" title=\"修改{baseTableDesc}\">',");
                        sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-edit\"></i>',");
                        sb.AppendLine($"{tabTre}    '</a>'];");
                        sb.AppendLine($"{tabTre}");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"{tabTre}let enable = ['  <a class=\"enable\" href=\"javascript:void(0)\" title=\"启用{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-ok\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"{tabTre}");
                            sb.AppendLine($"{tabTre}let disable = ['  <a class=\"disable\" href=\"javascript:void(0)\" title=\"禁用{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-ban-circle\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"{tabTre}");
                            sb.AppendLine($"{tabTre}let remove = ['  <a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"{tabTre}");
                            sb.AppendLine($"{tabTre}// 数据状态：0-正常；1-禁用；2-删除");
                            sb.AppendLine($"{tabTre}if (row.State == 0) {{");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(disable);");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(remove);");
                            sb.AppendLine($"{tabTre}}}");
                            sb.AppendLine($"{tabTre}if (row.State == 1) {{");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(enable);");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(remove);");
                            sb.AppendLine($"{tabTre}}}");
                            sb.AppendLine($"{tabTre}if (row.State == 2) {{");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(enable);");
                            sb.AppendLine($"{tabTre}    edit = edit.concat(disable);");
                            sb.AppendLine($"{tabTre}}}");
                            sb.AppendLine($"{tabTre}");
                        }
                        else
                        {
                            sb.AppendLine($"{tabTre}let remove = ['  <a class=\"remove\" href=\"javascript:void(0)\" title=\"删除{baseTableDesc}\">',");
                            sb.AppendLine($"{tabTre}    '<i class=\"glyphicon glyphicon-remove\"></i>',");
                            sb.AppendLine($"{tabTre}    '</a>'];");
                            sb.AppendLine($"{tabTre}edit = edit.concat(remove);");
                        }

                        sb.AppendLine($"{tabTre}return edit.join('');");

                        sb.AppendLine($"{tabTwo}}}");
                        sb.AppendLine($"{tabTwo}");
                        sb.AppendLine($"{tabTwo}// 操作事件响应");
                        sb.AppendLine($"{tabTwo}window.operateEvents = {{");
                        sb.AppendLine($"{tabTre}'click .edit': function (e, value, row, index) {{");
                        sb.AppendLine($"{tabTre}    //alert('You click edit action, row: ' + JSON.stringify(row));");
                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}    //debugger;");
                        sb.AppendLine($"{tabTre}    //console.info(\"编辑前获取行数据：\");");
                        sb.AppendLine($"{tabTre}    console.info(row);");
                        sb.AppendLine($"{tabTre}");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】                  

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            //if (column.Queryable == 1)
                            //{
                            //if (column.Name.IndexOf("State") > -1
                            //    //|| column.Name.IndexOf("CreatorId") > -1
                            //    //|| column.Name.IndexOf("CreateTime") > -1
                            //    //|| column.Name.IndexOf("LastModifierId") > -1
                            //    //|| column.Name.IndexOf("LastModifyTime") > -1
                            //    //|| column.Name.IndexOf("ModifierId") > -1
                            //    //|| column.Name.IndexOf("ModifiedTime") > -1
                            //    )
                            //{
                            //    sb.AppendLine($"{tabTre}    //$(\"#{columnName}\").val(row.{columnName}); // {columnDesc}");
                            //}
                            //else
                            //{}                    
                            //}
                            //else
                            //{
                            //    sb.AppendLine($"{tabTre}    //$(\"#{columnName}\").val(row.{columnName}); // {columnDesc}");
                            //}

                            //if (column.DataType == "datetime")
                            //{
                            //    dateInput = true; // 有日期输入字段
                            //}

                            sb.AppendLine($"{tabTre}    $(\"#{columnName}\").val(row.{columnName}); // {columnDesc}");

                        }

                        sb.AppendLine($"{tabTre}");
                        sb.AppendLine($"{tabTre}    $(\"#editModelLabel\").html(\"{baseTableDesc}信息修改\");");
                        sb.AppendLine($"{tabTre}    $('#editModel').modal('toggle');");
                        sb.AppendLine($"{tabTre}}},");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"{tabTre}'click .enable': function (e, value, row, index) {{");
                            sb.AppendLine($"{tabTre}	Enable(row[key]); // 启用行数据");
                            sb.AppendLine($"{tabTre}}}, 'click .disable': function (e, value, row, index) {{");
                            sb.AppendLine($"{tabTre}	Disable(row[key]); // 禁用行数据");
                        }
                        sb.AppendLine($"{tabTre}'click .remove': function (e, value, row, index) {{");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"{tabTre}    LogicalDelete(row[key]); // 逻辑删除行数据");
                        }
                        else
                        {
                            //sb.AppendLine($"{tabTre}$table.bootstrapTable('remove', {{");
                            //sb.AppendLine($"{tabTre}	field: key,");
                            //sb.AppendLine($"{tabTre}	values: [row[key]]");
                            //sb.AppendLine($"{tabTre}}});");
                            sb.AppendLine($"{tabTre}Delete(row[key]); // 删除行数据");
                        }

                        sb.AppendLine($"{tabTre}}}");
                        sb.AppendLine($"{tabTwo}}};");
                        sb.AppendLine($"{tabTwo}");

                        //sb.AppendLine($"{tabTwo}// 获取内容高度");
                        //sb.AppendLine($"{tabTwo}function getHeight() {{");
                        //sb.AppendLine($"{tabTre}var heightCorrection = 35;");
                        //sb.AppendLine($"{tabTre}return $(window).height() - $('h2').outerHeight(true) - heightCorrection;");
                        //sb.AppendLine($"{tabTwo}}}");
                        //sb.AppendLine($"");

                        if (isLogicalDelete)
                        {
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 启用数据");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"");
                            sb.AppendLine($"function Enable(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要启用该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{resourceName}/{controllerName}/Enable/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'id':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 禁用数据");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"");
                            sb.AppendLine($"function Disable(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要禁用该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{resourceName}/{controllerName}/Disable/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'id':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 逻辑删除");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function LogicalDelete(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要逻辑删除该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{resourceName}/{controllerName}/LogicalDelete/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'id':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 批量逻辑删除");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function BatchLogicalDelete(ids) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要批量逻辑删除这些{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{resourceName}/{controllerName}/BatchLogicalDelete/\" + ids + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'ids':''}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                        }
                        else
                        {
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 物理删除数据");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function Delete(id) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要删除该{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{resourceName}/{controllerName}/Delete/\" + id + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'id':'\" + id + \"'}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"/// <summary>");
                            sb.AppendLine($"/// 批量物理删除");
                            sb.AppendLine($"/// </summary>");
                            sb.AppendLine($"function BatchDelete(ids) {{");
                            sb.AppendLine($"	if (confirm(\"您确定要批量删除这些{baseTableDesc}吗？\")) {{");
                            sb.AppendLine($"		$.ajax({{");
                            sb.AppendLine($"			type: \"POST\",");
                            sb.AppendLine($"			url: \"/{resourceName}/{controllerName}/BatchDelete/\" + ids + \"?rnd=\" + (Math.random() * 10),");
                            //sb.AppendLine($"			data: \"{{'ids':'\" + ids + \"'}}\",");
                            sb.AppendLine($"			contentType: \"application/json; charset=utf-8\",");
                            sb.AppendLine($"			dataType: \"json\",");
                            sb.AppendLine($"			success: function (rst) {{");
                            sb.AppendLine($"				//console.info(rst);");
                            sb.AppendLine($"				if (rst && rst.success) {{");
                            sb.AppendLine($"					refreshTable();");
                            sb.AppendLine($"					toastr.success(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}} else {{");
                            sb.AppendLine($"					modals.error(rst.message ?? rst.Message);");
                            sb.AppendLine($"				}}");
                            sb.AppendLine($"			}}");
                            sb.AppendLine($"		}});");
                            sb.AppendLine($"	}}");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                        }

                        sb.AppendLine($"{tabTwo}$(function () {{");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$('#editModel').on('hidden.bs.modal', function () {{ // 关闭模态窗体事件");
                        sb.AppendLine($"{tabTre}    $(\"#editModel form\")[0].reset();");
                        sb.AppendLine($"{tabTre}    $(\"#btnSave\").prop(\"disabled\", false); // 解除保存按钮禁用");
                        sb.AppendLine($"{tabTre}    $(\"#editModel form input[type='hidden']\").val(\"\");");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}$(\"#btnSave\").off(\"click\").on(\"click\", function () {{ // {baseTableDesc}数据保存");
                        sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述                 

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            sb.AppendLine($"{tabTre}    let txt{columnName} = $(\"#{columnName}\").val(); // {columnDesc}");

                        }

                        sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            if (NoHandlerColumn(column))
                            {
                                // 不处理
                            }
                            else
                            {
                                // 必填项
                                if (columnName == "Name" || column.Nullable == 0)
                                {
                                    // https://codeseven.github.io/toastr/
                                    sb.AppendLine($"{tabTre}    if ( txt{columnName} == undefined || txt{columnName}.length == 0) {{");
                                    sb.AppendLine($"{tabTre}        toastr.error('请填写{baseColumnDesc}名称！');");
                                    sb.AppendLine($"{tabTre}        $(\"#{columnName}\").focus();");
                                    sb.AppendLine($"{tabTre}        return;");
                                    sb.AppendLine($"{tabTre}    }}");
                                }
                            }
                        }

                        sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述                    

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            //if (NoHandlerColumn(column))
                            //{
                            //    // 不处理
                            //}
                            //else{}

                            // 数值项
                            if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                            {
                                sb.AppendLine($"{tabTre}    if (txt{columnName} == undefined || txt{columnName}.length == 0) {{");
                                sb.AppendLine($"{tabTre}        txt{columnName} = \"0\";");
                                sb.AppendLine($"{tabTre}    }}");
                            }
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    // 字符串输入超长处理");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】
                            if (columnDesc != baseColumnDesc) continue; // 列描述中有冒号的不提示，一般是下拉数据

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            if (column.DataType!.ToLower().Contains("char") && column.Length > 0 && column.Length < 50)
                            {
                                sb.AppendLine($"{tabTre}    if (txt{columnName} && txt{columnName}.length > {column.Length}) {{");
                                sb.AppendLine($"{tabTre}        toastr.error('{baseColumnDesc}超过设定长度{column.Length}！');");
                                sb.AppendLine($"{tabTre}        $(\"#{columnName}\").focus();");
                                sb.AppendLine($"{tabTre}        return;");
                                sb.AppendLine($"{tabTre}    }}");
                            }
                        }

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    $(\"#btnSave\").prop(\"disabled\", \"disabled\");");

                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    // 字符串中异常字符处理");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            // 文本字段检查异常字符
                            if (column.DataType!.Contains("char") || column.DataType!.Contains("text"))
                            {
                                // /'%7C%5C%5C%7C%5C/%7C%5C%22%7C%5C%7C%7C%3E%7C%3C%7C%5C*%7C%5C?%7C:/g
                                var matchString = "%2F'%7C%5C%5C%7C%5C%22%7C%5C%7C%7C%3E%7C%3C%7C%5C*%7C%5C%3F%2Fg";
                                matchString = HttpUtility.UrlDecode(matchString);
                                sb.AppendLine($"{tabTre}    if (txt{columnName} != undefined && txt{columnName}.length > 0) {{");
                                sb.AppendLine($"{tabTre}        txt{columnName} = txt{columnName}.replace({matchString}, \"\"); // {columnDesc}");
                                sb.AppendLine($"{tabTre}    }}");
                            }
                        }

                        sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    var strJson = \"{{\";");
                        sb.AppendLine($"{tabTre}    let obj = {{}};");
                        //sb.AppendLine($"");

                        foreach (var column in tableColumn)
                        {
                            // 默认日期类型自动不参与增改
                            if (column.DataType == "timestamp") continue;

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            //if (NoHandlerColumn(column))
                            //{
                            //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\" + txt{columnName} + \",\"; // {columnDesc}");
                            //    }
                            //    else
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\\\"\" + txt{columnName} + \"\\\",\"; // {columnDesc}");
                            //    }
                            //}
                            //else
                            //{
                            //    if (column.Length > 0 && column.DataType!.ToLower().Contains("int"))
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\" + txt{columnName} + \",\"; // {columnDesc}");
                            //    }
                            //    else
                            //    {
                            //        sb.AppendLine($"{tabTre}    strJson += \"\\\"{columnName}\\\":\\\"\" + txt{columnName} + \"\\\",\"; // {columnDesc}");
                            //    }
                            //}

                            sb.AppendLine($"{tabTre}    obj.{columnName} = txt{columnName}; // {columnDesc}");
                        }

                        sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    strJson = strJson.rTrim(\",\"); // 清除右边的逗号");
                        //sb.AppendLine($"{tabTre}    strJson += \"}}\";");
                        //sb.AppendLine($"");
                        //sb.AppendLine($"{tabTre}    //console.info(\"保存提交前数据：\");");
                        //sb.AppendLine($"{tabTre}    //console.info(strJson);");
                        sb.AppendLine($"{tabTre}    //console.info(JSON.stringify(obj));");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}    $.ajax({{");
                        sb.AppendLine($"{tabTre}        type: \"POST\",");
                        sb.AppendLine($"{tabTre}        url: \"/{resourceName}/{controllerName}/Save/?rnd=\" + (Math.random() * 10),");
                        sb.AppendLine($"{tabTre}        data: JSON.stringify(obj),");
                        //sb.AppendLine($"{tabTre}        data: \"{{'json':'\" + encodeURIComponent(strJson) + \"'}}\",");
                        sb.AppendLine($"{tabTre}        contentType: \"application/json; charset=utf-8\",");
                        sb.AppendLine($"{tabTre}        dataType: \"json\",");
                        sb.AppendLine($"{tabTre}        success: function (rst) {{");
                        sb.AppendLine($"{tabTre}            //console.info(rst);");
                        sb.AppendLine($"{tabTre}            if (rst && rst.success) {{");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}                refreshTable();");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTre}                $(\"#editModel\").modal(\"hide\");");
                        sb.AppendLine($"{tabTre}                $(\"#btnSave\").prop(\"disabled\", \"\");");
                        sb.AppendLine($"{tabTre}                toastr.success(rst.message ?? rst.Message);");
                        sb.AppendLine($"{tabTre}            }} else {{");
                        sb.AppendLine($"{tabTre}                $.alert({{title: \"错误提示!\", content: rst.message }});");
                        sb.AppendLine($"{tabTre}            }}");
                        sb.AppendLine($"{tabTre}        }}");
                        sb.AppendLine($"{tabTre}    }});");
                        sb.AppendLine($"{tabTre}}});");
                        sb.AppendLine($"");
                        sb.AppendLine($"{tabTwo}}});");
                        sb.AppendLine($"");

                        File.WriteAllText(jsPath, sb.ToString(), utf8);


                        /* CSS 文件处理*/

                        sb = new();

                        sb.AppendLine($"/**");
                        sb.AppendLine($" * {baseTableDesc}");
                        sb.AppendLine($" * */");
                        sb.AppendLine($"");

                        if (isTree)
                        {
                            sb.AppendLine($"        #tree {{");
                            sb.AppendLine($"            margin-top: 10px;");
                            sb.AppendLine($"        }}");
                            sb.AppendLine($"");
                            sb.AppendLine($".modal-body .form-row label,");
                            sb.AppendLine($".modal-body form.form-horizontal .form-group label {{");
                            sb.AppendLine($"    text-align: right;");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($".bs-glyphicons {{");
                            sb.AppendLine($"    overflow: hidden;");
                            sb.AppendLine($"    margin: 2px -5px 0;");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($"    .bs-glyphicons h4 {{");
                            sb.AppendLine($"        padding-left: 5px;");
                            sb.AppendLine($"        margin-bottom: 8px;");
                            sb.AppendLine($"        font-size: 1.0rem;");
                            sb.AppendLine($"    }}");
                            sb.AppendLine($"");
                            sb.AppendLine($".bs-glyphicons-list {{");
                            sb.AppendLine($"    padding-left: 0;");
                            sb.AppendLine($"    list-style: none;");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($".bs-glyphicons li {{");
                            sb.AppendLine($"    float: left;");
                            sb.AppendLine($"    width: 48px;");
                            sb.AppendLine($"    height: 48px;");
                            sb.AppendLine($"    padding: 10px;");
                            sb.AppendLine($"    font-size: 10px;");
                            sb.AppendLine($"    line-height: 1.4;");
                            sb.AppendLine($"    text-align: center;");
                            sb.AppendLine($"    background-color: #f9f9f9;");
                            sb.AppendLine($"    border: 1px solid #fff;");
                            sb.AppendLine($"    cursor: pointer;");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($".bs-glyphicons .glyphicon,");
                            sb.AppendLine($".bs-glyphicons .filetypes,");
                            sb.AppendLine($".bs-glyphicons .fa {{");
                            sb.AppendLine($"    margin-bottom: 5px;");
                            sb.AppendLine($"    font-size: 24px;");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($".bs-glyphicons li:hover {{");
                            sb.AppendLine($"    color: #fff;");
                            sb.AppendLine($"    background-color: #563d7c;");
                            sb.AppendLine($"}}");
                            sb.AppendLine($"");
                            sb.AppendLine($".icon-selected {{");
                            sb.AppendLine($"    color: #00bfff;");
                            sb.AppendLine($"}}");
                        }

                        sb.AppendLine($"        td {{");
                        sb.AppendLine($"            text-overflow: ellipsis;");
                        sb.AppendLine($"            white-space: nowrap;");
                        sb.AppendLine($"            overflow: hidden;");
                        sb.AppendLine($"            word-break: keep-all;");
                        sb.AppendLine($"        }}");

                        File.WriteAllText(cssPath, sb.ToString(), utf8);

                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"6）生成前端资源文件输出错误", ex);
                throw;
            }
        }

        #endregion

        #region 7）其他输出

        /// <summary>
        /// 其他输出文件
        /// </summary>
        /// <param name="dbName">数据库名称</param>       
        /// <param name="selectPath">输出文件根目录</param>
        /// <param name="tableList">表数据列表</param>
        /// <param name="columnList">列数据列表</param>
        /// <param name="referenceList">表引用列表</param>
        /// <param name="indexList">表索引列表</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        private void CreateOtherFile(string dbName, string selectPath, List<Tables> tableList, List<Columns> columnList, List<DbReferences> referenceList, List<DbIndexs>? indexList = null)
        {
            //if (string.IsNullOrEmpty(dbName))
            //{
            //    throw new ArgumentException($"“{nameof(dbName)}”不能为 Null 或空。", nameof(dbName));
            //}

            if (string.IsNullOrEmpty(selectPath))
            {
                throw new ArgumentException($"“{nameof(selectPath)}”不能为 Null 或空。", nameof(selectPath));
            }

            if (tableList is null)
            {
                throw new ArgumentNullException(nameof(tableList));
            }

            // 1 输出菜单
            // 2 增删改视图标题
            // 3 关系映射

            #region (1) 输出菜单

            var menuFilePath = $"{selectPath}\\MenusHtml.cs";
            var adminlteMenuFilePath = $"{selectPath}\\AdminLTEMenusHtml.cs";
            var menuSqlPath = $"{selectPath}\\SystemMenus.sql";
            StringBuilder menuSb = new();
            StringBuilder adminlteSb = new();
            StringBuilder sqlSb = new();
            Dictionary<string, string> menuTitleList = new();

            try
            {
                int i = 0, j = 10, s = 0;
                foreach (var table in tableList)
                {
                    var str = table.Name.Split('_')[0];

                    if (!menuTitleList.ContainsKey(str))
                    {
                        menuTitleList.Add(str, str);
                    }
                }

                sqlSb.AppendLine($"");
                sqlSb.AppendLine($"INSERT INTO `auth_menus` ");
                sqlSb.AppendLine($"(`Id`,`PId`,`Name`,`Url`,`SortNumber`,`Disabled`) VALUES");

                foreach (KeyValuePair<string, string> keyValue in menuTitleList)
                {
                    i++; s = 0;
                    var title = keyValue.Value;

                    if (i == 1)
                    {
                        sqlSb.AppendLine($"({i}, 0, '{title}', '', {i}, 0)");
                    }
                    else
                    {
                        sqlSb.AppendLine($", ({i}, 0, '{title}', '', {i}, 0)");
                    }

                    #region AdminLTE Menu

                    if (i == 1)
                    {
                        adminlteSb.AppendLine($"<li class=\"nav-item has-treeview menu-open\">");
                        adminlteSb.AppendLine($"{tabOne}<a href=\"#\" class=\"nav-link active\">");
                    }
                    else
                    {
                        adminlteSb.AppendLine($"<li class=\"nav-item has-treeview\">");
                        adminlteSb.AppendLine($"{tabOne}<a href=\"#\" class=\"nav-link\">");
                    }

                    adminlteSb.AppendLine($"{tabTwo}<i class=\"fa fa-book nav-icon\"></i>");
                    adminlteSb.AppendLine($"{tabTwo}<p>");
                    adminlteSb.AppendLine($"{tabTre}{title}");
                    adminlteSb.AppendLine($"{tabTre}<i class=\"right fa fa-angle-left\"></i>");
                    adminlteSb.AppendLine($"{tabTwo}</p>");
                    adminlteSb.AppendLine($"{tabOne}</a>");
                    adminlteSb.AppendLine($"{tabOne}<ul class=\"nav nav-treeview\">");

                    #endregion

                    menuSb.AppendLine($"<h5 class=\"sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted\">");
                    menuSb.AppendLine($"{tabOne}<span>{title}</span>");
                    menuSb.AppendLine($"{tabOne}<a class=\"d-flex align-items-center text-muted\" href=\"#\" aria-label=\"Add a new report\">");
                    menuSb.AppendLine($"{tabTwo}<span data-feather=\"plus-circle\"></span>");
                    menuSb.AppendLine($"{tabOne}</a>");
                    menuSb.AppendLine($"</h5>");

                    // 表列项数据
                    var tables = tableList.Where(entity => entity.Name.StartsWith(title)).ToList();

                    menuSb.AppendLine($"<ul class=\"nav flex-column mb-2\">");

                    foreach (var table in tables)
                    {
                        var tableName = table.Name; // 表名
                        if (table.Comment == null) continue;
                        var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                        var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】
                        var area = title.ToUpperFirst();
                        var controller = GetControllerName(tableName);
                        if (!string.IsNullOrEmpty(controller) && !string.IsNullOrEmpty(area))
                            controller = controller.Replace(area, ""); // 控制器名去掉前面的去域名                        

                        var tableColumn = columnList.Where(entity => entity.TableName == tableName).ToList();
                        var isTree = IsTree(tableColumn); // 是否树结构表
                        var pageName = "TableList";
                        if (isTree)
                        {
                            pageName = "TreeList";
                        }
                        var munuUrl = $"/{area}/{controller}/{pageName}";

                        j++; s++;
                        sqlSb.AppendLine($", ({j}, {i}, '{baseTableDesc}', '{munuUrl}', {s}, 0)");

                        #region AdminLTE Menu

                        //adminlteSb.AppendLine($"<li class=\"nav-item\">");
                        //adminlteSb.AppendLine($"{tabOne}<a href=\"{munuUrl}\" class=\"nav-link\">");
                        //adminlteSb.AppendLine($"{tabOne}<i class=\"fa fa-circle nav-icon\"></i>");
                        //adminlteSb.AppendLine($"{tabOne}<p>{baseTableDesc}</p>");
                        //adminlteSb.AppendLine($"{tabOne}</a>");
                        //adminlteSb.AppendLine($"</li> ");

                        adminlteSb.AppendLine($"{tabTwo}<li class=\"nav-item\">");
                        adminlteSb.AppendLine($"{tabTre}<a href=\"{munuUrl}\" class=\"nav-link\">");
                        adminlteSb.AppendLine($"{tabTre}	<i class=\"fa fa-circle nav-icon\"></i>");
                        adminlteSb.AppendLine($"{tabTre}	<p>{baseTableDesc}</p>");
                        adminlteSb.AppendLine($"{tabTre}</a>");
                        adminlteSb.AppendLine($"{tabTwo}</li>");

                        #endregion

                        menuSb.AppendLine($"{tabOne}<li class=\"nav-item\">");
                        menuSb.AppendLine($"{tabTwo}<a class=\"nav-link\" href=\"{munuUrl}\">");
                        menuSb.AppendLine($"{tabTre}<span data-feather=\"file-text\"></span>");
                        menuSb.AppendLine($"{tabTre}{baseTableDesc}");
                        menuSb.AppendLine($"{tabTwo}</a>");
                        menuSb.AppendLine($"{tabOne}</li>");
                    }

                    adminlteSb.AppendLine($"	</ul>");
                    adminlteSb.AppendLine($"</li>");
                    adminlteSb.AppendLine($"");

                    menuSb.AppendLine($"</ul>");

                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"7）其他输出，(1) 输出菜单输出错误", ex);
                throw;
            }

            File.WriteAllText(menuFilePath, menuSb.ToString());
            File.WriteAllText(adminlteMenuFilePath, adminlteSb.ToString());
            File.WriteAllText(menuSqlPath, sqlSb.ToString());

            #endregion

            #region (2) 增删改视图标题

            var viewFilePath = $"{selectPath}\\ViewsHtml.cs";
            StringBuilder viewSb = new();

            try
            {
                var i = 1;
                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 表名
                    if (table.Comment == null) continue;
                    var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                    var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】
                    var className = GetClassName(tableName);
                    viewSb.AppendLine($"{i}) <h4>{className}</h4> <h4>{baseTableDesc}</h4>");
                    i++;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"7）其他输出，(2) 增删改视图标题输出错误", ex);
                throw;
            }

            File.WriteAllText(viewFilePath, viewSb.ToString());

            #endregion

            #region (3) 关系映射

            var mapperFilePath = $"{selectPath}\\ModelDtoMapper.cs";
            StringBuilder mapperSb = new();

            try
            {
                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 表名
                    if (table.Comment == null) continue;
                    var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                    var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】
                    var className = tableName.ToSingularModelName();
                    var dtoName = className + "Dto"; // 表Dto对象
                    mapperSb.AppendLine($"CreateMap<{className}, {dtoName}>().ReverseMap(); // {baseTableDesc}");
                }

                mapperSb.AppendLine($"");

                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 表名
                    if (table.Comment == null) continue;
                    var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                    var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】
                    var className = tableName.ToSingularModelName();
                    var dtoName = className + "Dto"; // 表Dto对象
                    var viewModelName = className + "ViewModel"; // 表ViewModel对象
                    mapperSb.AppendLine($"CreateMap<{dtoName}, {viewModelName}>(); // {baseTableDesc}");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"7）其他输出，(3) 关系映射输出错误", ex);
                throw;
            }

            File.WriteAllText(mapperFilePath, mapperSb.ToString());

            #endregion

            #region (4) 数据库清库

            var truncateFilePath = $"{selectPath}\\TruncateTableSql.cs";
            StringBuilder truncateSb = new();

            try
            {
                foreach (var table in tableList)
                {
                    var tableName = table.Name; // 表名
                    if (table.Comment == null) continue;
                    var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                    var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】

                    truncateSb.AppendLine($"TRUNCATE TABLE {tableName}; # {baseTableDesc}");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"7）其他输出，(4) 数据库清库输出错误", ex);
                throw;
            }

            File.WriteAllText(truncateFilePath, truncateSb.ToString());

            #endregion

            #region (5) Ef Core 数据库上下文

            if (!string.IsNullOrEmpty(dbName))
            {
                var contextFilePath = $"{selectPath}\\{dbName}Context.cs";
                StringBuilder contextSb = new();

                try
                {
                    #region 数据库上下文表类声明

                    foreach (var table in tableList)
                    {
                        var tableName = table.Name; // 表名
                        var dbSetsName = tableName.ToPluralizeModelName();
                        var className = tableName.ToSingularModelName();
                        if (table.Comment == null) continue;
                        var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                        var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】

                        contextSb.AppendLine($"{tabOne}/// <summary>");
                        contextSb.AppendLine($"{tabOne}/// {baseTableDesc}");
                        contextSb.AppendLine($"{tabOne}/// </summary>");
                        contextSb.AppendLine($"{tabOne}public virtual DbSet<{className}> {dbSetsName} {{ get; set; }}");
                        contextSb.AppendLine($"{tabOne}");
                    }

                    contextSb.AppendLine($"{tabOne}");
                    contextSb.AppendLine($"{tabOne}");

                    #endregion

                    #region 数据库上下文表字段声明

                    foreach (var table in tableList)
                    {
                        var tableName = table.Name; // 表名
                        var className = tableName.ToSingularModelName();
                        if (table.Comment == null) continue;
                        var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                        var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】

                        contextSb.AppendLine($"{tabOne}modelBuilder.Entity<{className}>(entity =>");
                        contextSb.AppendLine($"{tabOne}{{");
                        if (string.IsNullOrEmpty(tableDesc))
                        {
                            contextSb.AppendLine($"{tabTwo}entity.ToTable(\"{tableName}\");");
                        }
                        else
                        {
                            contextSb.AppendLine($"{tabTwo}entity.ToTable(\"{tableName}\", tb => tb.HasComment(\"{tableDesc}\"));");
                        }
                        contextSb.AppendLine($"{tabOne}");
                        //contextSb.AppendLine($"{tabTwo}entity.HasComment(\"{tableDesc}\");");                        

                        #region 索引数据处理

                        var indexs = indexList?.Where(e => e.TableName == tableName).ToList();

                        if (indexs != null)
                        {
                            foreach (var index in indexs)
                            {
                                var indexColString = string.Empty;
                                var colNames = index.IndexColumns;
                                if (colNames != null)
                                {
                                    var indexCol = string.Empty;
                                    var colArr = colNames.Split(',');
                                    foreach (var col in colArr)
                                    {
                                        var colName = GetColumnName(col);
                                        indexCol += "e." + colName + ",";
                                    }
                                    indexCol = indexCol.Trim().Trim(',');
                                    if (colArr.Length == 1)
                                    {
                                        indexColString = indexCol;
                                    }
                                    else
                                    {
                                        indexColString = $"new {{{indexCol}}}";
                                    }
                                }

                                if (index.NonUnique == 0)
                                {
                                    // 唯一性索引
                                    contextSb.AppendLine($"{tabTwo}entity.HasKey(e => {indexColString}).HasName(\"{index.IndexName}\");");
                                    contextSb.AppendLine($"{tabOne}");
                                }
                                else
                                {
                                    // 普通索引
                                    contextSb.AppendLine($"{tabTwo}entity.HasIndex(e => {indexColString}, \"{index.IndexName}\");");
                                    contextSb.AppendLine($"{tabOne}");
                                }
                            }
                        }

                        #endregion

                        #region 表列项数据

                        // 表列项数据
                        var tableColumn = columnList.Where(entity => entity.TableName == tableName).ToList();

                        foreach (var column in tableColumn)
                        {
                            if (column.DataType!.ToLower() == "timestamp")
                            {
                                continue;
                            }

                            var columnName = column.Name; // 列名
                            var columnDesc = column.Comment?.Replace(":", "："); // 列描述【列基本描述：枚举描述】
                            columnDesc = columnDesc.Replace("\n", ""); // 处理换行符
                            if (string.IsNullOrEmpty(columnDesc)) columnDesc = columnName;
                            var baseColumnDesc = columnDesc?.Split('：')[0]; // 列基本描述【描述中冒号前面的部分】                            

                            #region Column特性

                            var customColumnName = GetColumnName(columnName);
                            if (columnName != customColumnName)
                            {
                                columnName = customColumnName;
                            }

                            #endregion

                            // int
                            if (column.DataType!.ToLower() == "int")
                            {
                                contextSb.AppendLine($"{tabTwo}entity.Property(e => e.{columnName})");
                                contextSb.AppendLine($"{tabTre}.HasColumnType(\"{column.ColumnType}\")");
                                if (!string.IsNullOrEmpty(column.DefaultValue))
                                {
                                    contextSb.AppendLine($"{tabTre}.HasDefaultValueSql(\"'{column.DefaultValue}'\")");
                                }
                                contextSb.AppendLine($"{tabTre}.HasComment(\"{columnDesc}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }

                            // decimal
                            else if (column.DataType!.ToLower() == "decimal")
                            {
                                contextSb.AppendLine($"{tabTwo}entity.Property(e => e.{columnName})");
                                contextSb.AppendLine($"{tabTre}.HasColumnType(\"{column.ColumnType}\")");
                                if (!string.IsNullOrEmpty(column.DefaultValue))
                                {
                                    contextSb.AppendLine($"{tabTre}.HasDefaultValueSql(\"'{column.DefaultValue}'\")");
                                }
                                contextSb.AppendLine($"{tabTre}.HasComment(\"{columnDesc}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }

                            // char
                            else if (column.DataType!.ToLower().Contains("char"))
                            {
                                contextSb.AppendLine($"{tabTwo}entity.Property(e => e.{columnName})");
                                contextSb.AppendLine($"{tabTre}.HasMaxLength({column.Length})");
                                contextSb.AppendLine($"{tabTre}.IsUnicode(false)");
                                contextSb.AppendLine($"{tabTre}.HasComment(\"{columnDesc}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }

                            // datetime
                            else if (column.DataType!.ToLower() == "datetime")
                            {
                                contextSb.AppendLine($"{tabTwo}entity.Property(e => e.{columnName})");
                                contextSb.AppendLine($"{tabTre}.HasComment(\"{columnDesc}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }

                            // date
                            else if (column.DataType!.ToLower() == "date")
                            {
                                contextSb.AppendLine($"{tabTwo}entity.Property(e => e.{columnName})");
                                contextSb.AppendLine($"{tabTre}.HasColumnType(\"{column.ColumnType}\")");
                                contextSb.AppendLine($"{tabTre}.HasComment(\"{columnDesc}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }
                            // text
                            else if (column.DataType!.ToLower().Contains("char"))
                            {
                                contextSb.AppendLine($"{tabTwo}entity.Property(e => e.{columnName})");
                                contextSb.AppendLine($"{tabTre}.HasColumnType(\"{column.ColumnType}\")");
                                contextSb.AppendLine($"{tabTre}.HasComment(\"{columnDesc}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }
                            // 其余
                            else
                            {
                                contextSb.AppendLine($"{tabTwo}entity.Property(e => e.{columnName})");
                                contextSb.AppendLine($"{tabTre}.HasComment(\"{columnDesc}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }
                        }

                        #endregion

                        #region 引用列数据（外键）处理

                        // 被引用数据
                        var referenceTable = referenceList?.Where(entity => entity.PrimarykeyTableName == tableName).ToList();

                        if (referenceTable?.Count > 0)
                        {
                            // 被引用的数据
                            foreach (var reference in referenceTable)
                            {
                                #region Column特性

                                var refColumnName = reference.PrimarykeyColumnName;
                                var customColumnName = GetColumnName(refColumnName);
                                if (reference.PrimarykeyColumnName != customColumnName)
                                {
                                    refColumnName = customColumnName;
                                }

                                var singularName = GetInstanceColumn(refColumnName);
                                if (string.IsNullOrEmpty(singularName))
                                {
                                    singularName = this.Singularize(reference.TableName);
                                }

                                #endregion

                                //contextSb.AppendLine($"{tabTwo}entity.HasIndex(e => e.{refColumnName}, \"{reference.ConstraintName}\");");
                                //contextSb.AppendLine($"{tabOne}");

                                contextSb.AppendLine($"{tabTwo}entity.HasOne(d => d.{singularName})");
                                contextSb.AppendLine($"{tabTre}.WithMany(p => p.{className})");
                                contextSb.AppendLine($"{tabTre}.HasForeignKey(d => d.{refColumnName})");
                                contextSb.AppendLine($"{tabTre}.HasConstraintName(\"{reference.ConstraintName}\");");
                                contextSb.AppendLine($"{tabOne}");
                            }
                        }

                        #endregion

                        contextSb.AppendLine($"{tabOne}}});");
                        contextSb.AppendLine($"{tabOne}");
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog($"7）其他输出，(5) Ef Core 数据库上下文输出错误", ex);
                    throw;
                }

                File.WriteAllText(contextFilePath, contextSb.ToString());
            }

            #endregion

            #region (6) 资源配置数据

            if (!string.IsNullOrEmpty(dbName))
            {
                var resourceFilePath = $"{selectPath}\\bundleconfig.json";
                StringBuilder resourceSb = new();

                try
                {
                    #region 区域名称汇总

                    Dictionary<string, string> areaList = AreaList(tableList);

                    #endregion

                    resourceSb.AppendLine($"[");

                    foreach (KeyValuePair<string, string> keyValue in areaList)
                    {
                        #region 检查区域及子目录

                        var title = keyValue.Value;
                        var areaName = title.ToUpperFirst(); // 区域名称

                        #endregion

                        #region 资源配置数据表类声明
                        // 表列项数据
                        var tables = tableList.Where(entity => entity.Name.StartsWith(title)).ToList();

                        foreach (var table in tables)
                        {
                            var tableName = table.Name; // 表名
                            var className = tableName.ToSingularModelName();
                            if (table.Comment == null) continue;
                            var tableDesc = table.Comment.Replace(":", "："); // 表描述                
                            var baseTableDesc = tableDesc.Split('：')[0].TrimEnd('表'); // 表基本描述【描述中冒号前面的部分】

                            var controllerName = GetControllerName(tableName);
                            controllerName = controllerName.Replace(areaName, ""); // 控制器名去掉前面的去域名
                            var resourcePath = $"{areaName}/{controllerName}";

                            var tableColumn = columnList.Where(entity => entity.TableName == tableName).ToList();
                            var isTree = IsTree(tableColumn); // 是否树结构表
                            var pageName = "TableList";
                            if (isTree)
                            {
                                pageName = "TreeList";
                            }

                            //resourceSb.AppendLine($"{tabOne}/// <summary>");
                            //resourceSb.AppendLine($"{tabOne}/// {baseTableDesc}");
                            //resourceSb.AppendLine($"{tabOne}/// </summary>");
                            //resourceSb.AppendLine($"{tabOne}public virtual DbSet<{className}>? {className} {{ get; set; }} = null!;");
                            //resourceSb.AppendLine($"{tabOne}");

                            resourceSb.AppendLine($"{tabOne}  {{ // {baseTableDesc}样式表");
                            resourceSb.AppendLine($"{tabOne}    \"outputFileName\": \"wwwroot/view-resources/{resourcePath}/TableList.min.css\",");
                            resourceSb.AppendLine($"{tabOne}    \"inputFiles\": [");
                            resourceSb.AppendLine($"{tabOne}      \"wwwroot/view-resources/{resourcePath}/TableList.css\"");
                            resourceSb.AppendLine($"{tabOne}    ]");
                            resourceSb.AppendLine($"{tabOne}  }},");
                            resourceSb.AppendLine($"{tabOne}  {{ // {baseTableDesc}JS脚本");
                            resourceSb.AppendLine($"{tabOne}    \"outputFileName\": \"wwwroot/view-resources/{resourcePath}/{pageName}.min.js\",");
                            resourceSb.AppendLine($"{tabOne}    \"inputFiles\": [");
                            resourceSb.AppendLine($"{tabOne}      \"wwwroot/view-resources/{resourcePath}/{pageName}.js\"");
                            resourceSb.AppendLine($"{tabOne}    ]");
                            resourceSb.AppendLine($"{tabOne}  }},");
                        }

                        #endregion
                    }

                    resourceSb.AppendLine($"]");
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog($"7）其他输出，(6) 资源配置数据输出错误", ex);
                    throw;
                }

                File.WriteAllText(resourceFilePath, resourceSb.ToString());
            }

            #endregion
        }

        /// <summary>
        /// 是否枚举字段
        /// </summary>
        /// <param name="desc">字段描述</param>
        /// <returns></returns>
        private bool IsEnumColumn(string desc)
        {
            if (desc.IndexOf("：") > -1 && desc.IndexOf("；") > -1)
                return true;

            return false;
        }

        /// <summary>
        /// 输出枚举文件，规划输出枚举数据库脚本
        /// </summary>
        /// <param name="selectPath"></param>
        /// <param name="enumList"></param>
        private void CreateEnumFile(string selectPath, List<Enumerate> enumList)
        {
            if (enumList == null || enumList.Count == 0) return;

            #region (4) 枚举字典

            var enumFilePath = $"{selectPath}\\EnumDictionary.cs";
            StringBuilder enumSb = new();

            try
            {
                //Dictionary<string, string> keyValues = new Dictionary<string, string>();

                foreach (var column in enumList)
                {
                    var columnName = column.Name; // 表名
                    var columnDesc = column.Comment?.Replace(":", "："); // 列描述   
                    var descArr = columnDesc?.Split('：');
                    var columnTitleDesc = descArr[0]; // 列基本描述【描述中冒号前面的部分】
                    var columnEnumDesc = descArr[1]; // 列枚举数据定义【描述中冒号后面的部分】

                    columnEnumDesc = columnEnumDesc.Replace(";", "；").Replace("、", "；").Replace("（", "(").Replace("，", ",");

                    if (columnEnumDesc.IndexOf("；") > -1)
                    {
                        var enumArr = columnEnumDesc.Split('；');
                        if (enumArr.Length == 1) continue;

                        //if (keyValues.ContainsKey(columnName)) continue;
                        //keyValues.Add(columnName, columnName);

                        enumSb.AppendLine($"/// <summary>");
                        enumSb.AppendLine($"/// {columnDesc}");
                        enumSb.AppendLine($"/// </summary>");
                        enumSb.AppendLine($"public enum Enum{columnName}");
                        enumSb.AppendLine($"{{");

                        for (int i = 0; i < enumArr.Length; i++)
                        {
                            // 0-待复核；1-复核通过；2-复核不通过
                            var enumEle = enumArr[i];
                            if (string.IsNullOrEmpty(enumEle)) continue;
                            var enumEleArr = enumEle.Split('-');
                            var idx = i;
                            var str = enumEleArr[0];
                            if (enumEleArr.Length > 1)
                            {
                                var idxStr = enumEleArr[0];
                                int.TryParse(idxStr, out idx);
                                if (idx == 0) idx = i;
                                str = enumEleArr[1];
                            }

                            var enumName = str.Replace("/", "或");
                            if (enumName.IndexOf("(") > -1) enumName = enumName.Split('(')[0];
                            if (enumName.IndexOf(",") > -1) enumName = enumName.Split(',')[0];

                            enumSb.AppendLine($"/// <summary>");
                            enumSb.AppendLine($"/// {str}");
                            enumSb.AppendLine($"/// </summary>");
                            enumSb.AppendLine($"[Display(Name = \"{str}\")]");
                            enumSb.AppendLine($"{enumName} = {idx},");
                        }

                        enumSb.AppendLine($"}}");
                        enumSb.AppendLine($"");
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"输出枚举文件，规划输出枚举数据库脚本", ex);
                throw;
            }

            File.WriteAllText(enumFilePath, enumSb.ToString());

            #endregion
        }

        #endregion

        #region 库表全选复选框选中事件


        /// <summary>
        /// 全选点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxAll = (CheckBox)sender;

            if (cbxAll.Checked)
            {
                for (int i = 0; i < this.tableCheckList.Items.Count; i++)
                {
                    this.tableCheckList.SetItemChecked(i, true);
                }
            }
            else
            {
                for (int i = 0; i < this.tableCheckList.Items.Count; i++)
                {
                    this.tableCheckList.SetItemChecked(i, false);
                }
            }
        }

        #endregion

        #region 是否逻辑删除复选框选中事件

        /// <summary>
        /// 是否逻辑删除复选框点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxLogicalDelete_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxLogicalDelete = (CheckBox)sender;
            CheckLogicalDelete(cbxLogicalDelete);
        }

        private static void CheckLogicalDelete(CheckBox cbxLogicalDelete)
        {
            if (cbxLogicalDelete.Checked)
            {
                isLogicalDelete = true;
            }
            else
            {
                isLogicalDelete = false;
            }
        }

        #endregion

        #region 是否实体继承基类选中事件

        /// <summary>
        /// 是否实体继承基类复选框选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxEntityInherits_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxInheritsBase = (CheckBox)sender;
            CheckEntityInherits(cbxInheritsBase);
        }

        private static void CheckEntityInherits(CheckBox cbxInheritsBase)
        {
            if (cbxInheritsBase.Checked)
            {
                isInheritsBase = true;
            }
            else
            {
                isInheritsBase = false;
            }
        }

        #endregion

        #region 实体属性是否添加特性

        /// <summary>
        /// 实体属性是否添加特性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxEntityAttribute_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxEntityAttribute = (CheckBox)sender;
            CheckEntityAttribute(cbxEntityAttribute);
        }

        private static void CheckEntityAttribute(CheckBox cbxEntityAttribute)
        {
            if (cbxEntityAttribute.Checked)
            {
                isEntityAttribute = true;
            }
            else
            {
                isEntityAttribute = false;
            }
        }

        #endregion

        #region 是否启用控制器日志

        /// <summary>
        /// 是否启用控制器日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxEnableLogging_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxEnableLogging = (CheckBox)sender;
            CheckEnableLogging(cbxEnableLogging);
        }

        private static void CheckEnableLogging(CheckBox cbxEnableLogging)
        {
            if (cbxEnableLogging.Checked)
            {
                isEnableLogging = true;
            }
            else
            {
                isEnableLogging = false;
            }
        }

        #endregion

        #region 是否启用分布式缓存

        /// <summary>
        /// 是否启用分布式缓存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxEnableCaching_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxEnableCaching = (CheckBox)sender;
            CheckEnableCaching(cbxEnableCaching);
        }

        private static void CheckEnableCaching(CheckBox cbxEnableCaching)
        {
            if (cbxEnableCaching.Checked)
            {
                isEnableCaching = true;
            }
            else
            {
                isEnableCaching = false;
            }
        }

        #endregion

        #region 数据库配置

        FormDbConfig frmDbConfig = null;

        /// <summary>
        /// 数据库配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDbConfig_Click(object sender, EventArgs e)
        {
            frmDbConfig = new FormDbConfig(OPType.新建);
        }

        #endregion

        #region 数据库连接

        /// <summary>
        /// 数据库连接点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDbConnect_Click(object sender, EventArgs e)
        {
            InitMain();
        }

        /// <summary>
        /// 初始化输入框
        /// </summary>
        /// <param name="ctl"></param>
        void InitTextBox(Control ctl)
        {
            foreach (Control parent in ctl.Controls)
            {
                if (parent.GetType().ToString() == "System.Windows.Forms.TextBox")
                    ((TextBox)parent).Text = "";
                foreach (Control c in parent.Controls)
                {
                    if (c.GetType().ToString() == "System.Windows.Forms.TextBox")
                        ((TextBox)c).Text = "";
                    InitTextBox(parent);
                }
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        [Obsolete]
        private void InitMain()
        {
            #region 控件初始化

            foreach (Control control in this.Controls)
                this.InitTextBox(control);

            this.cbxLogicalDelete.Checked = false;
            this.cbxEntityInherits.Checked = false;
            this.cbxEntityAttribute.Checked = false;
            this.cbxEnableLogging.Checked = false;
            this.cbxEnableCaching.Checked = false;
            this.cbxEfCoreAttribute.Checked = false;
            this.cbxSqlSugarAttribute.Checked = false;
            this.cbxDapperAttribute.Checked = false;

            #endregion

            var encodings = System.Text.Encoding.GetEncodings();
            var en = encodings;

            FormGrid frmGrid = new();
            DialogResult dialog = frmGrid.ShowDialog(this);

            if (dialog == DialogResult.OK || FormUtils.IsOK_Close) //当前窗体 是正常关闭的情况下
            {
                if (DbConfig != null)
                {
                    this.txtConnString.Text = DbConfig.ConnString;
                    this.txtLinkName.Text = DbConfig.Name;
                    this.txtDbType.Text = DbConfig.DBType;
                    strDbName = DbConfig.DBName;
                }

                if (RefMaterial != null)
                {
                    this.txtSpaceName.Text = RefMaterial.SpaceName;
                    this.txtControllerReferenceMaterials.Text = RefMaterial.Controller;
                    this.txtBllReferenceMaterials.Text = RefMaterial.Bll;
                    this.txtDalReferenceMaterials.Text = RefMaterial.Dal;
                    this.txtModelReferenceMaterials.Text = RefMaterial.Model;
                    this.txtEfContext.Text = RefMaterial.EfContext;

                    this.txtSavePath.Text = RefMaterial.SavePath;
                    DefaultSelectedPath = RefMaterial.SavePath;

                    isLogicalDelete = RefMaterial.LogicalDelete;
                    this.cbxLogicalDelete.Checked = RefMaterial.LogicalDelete;

                    isInheritsBase = RefMaterial.EntityInherits;
                    this.cbxEntityInherits.Checked = RefMaterial.EntityInherits;

                    isEntityAttribute = RefMaterial.EntityAttribute;
                    this.cbxEntityAttribute.Checked = RefMaterial.EntityAttribute;

                    isEnableLogging = RefMaterial.EnableLogging;
                    this.cbxEnableLogging.Checked = RefMaterial.EnableLogging;

                    isEnableCaching = RefMaterial.EnableCaching;
                    this.cbxEnableCaching.Checked = RefMaterial.EnableCaching;

                    isEfCoreAttribute = RefMaterial.EfCoreAttribute;
                    this.cbxEfCoreAttribute.Checked = RefMaterial.EfCoreAttribute;

                    isSqlSugarAttribute = RefMaterial.SqlSugarAttribute;
                    this.cbxSqlSugarAttribute.Checked = RefMaterial.SqlSugarAttribute;

                    isDapperAttribute = RefMaterial.DapperAttribute;
                    this.cbxDapperAttribute.Checked = RefMaterial.DapperAttribute;

                    isSingularEntity = RefMaterial.SingularEntity;
                    this.cbxSingularEntity.Checked = RefMaterial.SingularEntity;

                    bootstrapVersion = RefMaterial.BSVersion; // Bootstrap版本:4,5
                    rdbBootstrap4.Checked = bootstrapVersion == 4;
                    rdbBootstrap5.Checked = bootstrapVersion == 5;

                    // 系统框架：1-.Net Framework；2-.Net Core(.net)
                    frameworkVersion = RefMaterial.FrameworkVersion;
                    rdbNetFramework.Checked = frameworkVersion == 1;
                    rdbNetCore.Checked = frameworkVersion == 2;

                }

                var info = DBUtils.Instance?.Info;
                var dataSource = DBUtils.Instance?.Info?.TableNames;

                try
                {
                    databaseCheckList.Items.Clear();
                    if (info != null)
                    {
                        databaseCheckList.DataSource = info.DBNames; // 数据库
                        databaseCheckList.SelectedItem = info.DBName;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog($"初始化数据(1)", ex);
                    //throw;
                }

                for (int i = 0; i < this.databaseCheckList.Items.Count; i++)
                {
                    var na = this.databaseCheckList.Items[i].ToString();

                    if (this.databaseCheckList.Items[i].ToString() == info.DBName)
                    {
                        this.databaseCheckList.SetItemChecked(i, true);
                    }
                }

                try
                {
                    tableCheckList.DataSource = dataSource; // 表
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog($"初始化数据(2)", ex);
                    //throw;
                }

                FormUtils.IsOK_Close = false;
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 数据库连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDbLink_Click(object sender, EventArgs e)
        {
            InitMain();
        }

        #endregion

        #region 输出程序引用文件配置数据保存

        /// <summary>
        /// 文件输出根目录选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectSavePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new();
            path.ShowDialog();
            var selectedPath = path.SelectedPath;
            if (!selectedPath.Contains("Entity")) selectedPath += @"\Entity";
            this.txtSavePath.Text = selectedPath;
            DefaultSelectedPath = selectedPath;
        }

        /// <summary>
        /// 输出程序引用文件配置数据保存点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfigSave_Click(object sender, EventArgs e)
        {
            ReferenceMaterialSave();
        }

        /// <summary>
        /// 输出程序引用文件配置数据保存
        /// </summary>
        private void ReferenceMaterialSave()
        {
            if (string.IsNullOrWhiteSpace(txtSpaceName.Text))
            {
                MessageBox.Show("请输入命名空间！！");
                return;
            }

            if (DbConfig == null)
            {
                MessageBox.Show("请先连接数据库！！");
                return;
            }
            else
            {
                RefMaterial ??= new ReferenceMaterials();
                RefMaterial.DbId = DbConfig.Id;
                RefMaterial.SpaceName = this.txtSpaceName.Text.Trim();
                RefMaterial.Controller = this.txtControllerReferenceMaterials.Text.Trim();
                RefMaterial.Bll = this.txtBllReferenceMaterials.Text.Trim();
                RefMaterial.Dal = this.txtDalReferenceMaterials.Text.Trim();
                RefMaterial.Model = this.txtModelReferenceMaterials.Text.Trim();

                RefMaterial.LogicalDelete = this.cbxLogicalDelete.Checked;
                RefMaterial.EntityInherits = this.cbxEntityInherits.Checked;
                RefMaterial.EntityAttribute = this.cbxEntityAttribute.Checked;
                RefMaterial.EnableLogging = this.cbxEnableLogging.Checked;
                RefMaterial.EnableCaching = this.cbxEnableCaching.Checked;

                RefMaterial.SavePath = this.txtSavePath.Text.Trim();
                RefMaterial.EfContext = this.txtEfContext.Text.Trim();

                RefMaterial.EfCoreAttribute = this.cbxEfCoreAttribute.Checked;
                RefMaterial.SqlSugarAttribute = this.cbxSqlSugarAttribute.Checked;
                RefMaterial.DapperAttribute = this.cbxDapperAttribute.Checked;
                RefMaterial.SingularEntity = this.cbxSingularEntity.Checked;

                if (rdbBootstrap4.Checked) RefMaterial.BSVersion = 4;
                if (rdbBootstrap5.Checked) RefMaterial.BSVersion = 5;

                // 系统框架：1-.Net Framework；2-.Net Core(.net)
                if (rdbNetFramework.Checked) RefMaterial.FrameworkVersion = 1;
                if (rdbNetCore.Checked) RefMaterial.FrameworkVersion = 2;

                int rst;
                if (RefMaterial?.Id > 0)
                {
                    rst = configHelper.Update(RefMaterial);
                }
                else
                {
                    rst = configHelper.Add(RefMaterial);
                }

                MessageBox.Show($"输出程序引用文件配置数据保存{(rst > 0 ? "成功" : "失败")}！！");
            }
        }

        #endregion

        private static bool isEfCoreAttribute = false; // 实体属性是EfCore特性
        private static bool isSqlSugarAttribute = false; // 实体属性是SqlSugar特性
        private static bool isDapperAttribute = false; // 实体属性是Dapper特性

        #region 添加启用SqlSugar特性

        /// <summary>
        /// 添加启用SqlSugar特性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxSqlSugarAttribute_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxSqlSugarAttribute = (CheckBox)sender;
            CheckSqlSugarAttribute(cbxSqlSugarAttribute);
        }

        private static void CheckSqlSugarAttribute(CheckBox cbxSqlSugarAttribute)
        {
            if (cbxSqlSugarAttribute.Checked)
            {
                isSqlSugarAttribute = true;
            }
            else
            {
                isSqlSugarAttribute = false;
            }
        }

        #endregion

        #region 添加启用EfCore特性

        /// <summary>
        /// 添加启用EfCore特性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxEfCoreAttribute_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxEfCoreAttribute = (CheckBox)sender;
            CheckEfCoreAttribute(cbxEfCoreAttribute);
        }

        private static void CheckEfCoreAttribute(CheckBox cbxEfCoreAttribute)
        {
            if (cbxEfCoreAttribute.Checked)
            {
                isEfCoreAttribute = true;
            }
            else
            {
                isEfCoreAttribute = false;
            }
        }

        #endregion

        #region 添加启用Dapper特性

        /// <summary>
        /// 添加启用Dapper特性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxDapperAttribute_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxDapperAttribute = (CheckBox)sender;
            CheckDapperAttribute(cbxDapperAttribute);
        }

        private static void CheckDapperAttribute(CheckBox cbxDapperAttribute)
        {
            if (cbxDapperAttribute.Checked)
            {
                isDapperAttribute = true;
            }
            else
            {
                isDapperAttribute = false;
            }
        }

        #endregion

        #region 单数形式输出实体名

        /// <summary>
        /// 单数形式输出实体名复选框选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxSingularEntity_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbxSingularEntity = (CheckBox)sender;
            CheckSingularEntity(cbxSingularEntity);
        }

        private static void CheckSingularEntity(CheckBox cbxSingularEntity)
        {
            if (cbxSingularEntity.Checked)
            {
                isSingularEntity = true;
            }
            else
            {
                isSingularEntity = false;
            }
        }

        #endregion

    }
}
